logo

Lack of data validation - Web Service - Elixir


Need

Prevent injection attacks, server resource exhaustion, and improve the overall security by applying server-side data validation


Context

  1. Usage of Elixir (1.10 and above) for building scalable and fault-tolerant applications
  2. Usage of Plug and Cowboy for request handling and server management
  3. Usage of Ecto for data persistence

Description

Insecure Code Example

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.

Steps

  1. Import and use 'Plug.Conn' for better handling of the request context
  2. Create a new function to validate the user data
  3. In the validation function, check the length of the data and sanitize it to escape any dangerous characters
  4. In the POST handler, call this validation function before using the user data

Secure Code Example

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.


References

  • 186 - Lack of data validation - Web Service

  • Last updated

    2023/09/18