Lack of data validation - Web Service - Elixir

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

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

Description

Non compliant code

        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

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

Compliant code

        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