Lack of data validation - Web Service
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
1. Non compliant code
defmodule InsecureApp do
use Plug.Router
plug :match
plug :dispatch
post "/data" do
Repo.insert(%Data{content: user_data})...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.
2. 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
3. Secure code example
defmodule SecureApp do
use Plug.Router
import Plug.Conn
plug :match
plug :dispatch
if String.length(data) > 1000,...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