logo

XPath Injection Vulnerability - Elixir


Need

Prevent unauthorized data access through XPath Injection


Context

  1. Usage of Elixir (v1.10+) for building scalable and fault-tolerant applications
  2. Usage of sweet_xml for parsing and manipulating XML data
  3. Usage of XML data manipulation

Description

Insecure Code Example

def vulnerable(user_input) do
  {:ok, doc} = File.read('data.xml')
  xpath = "//user[username/text() = '" <> user_input <> "']"
  SweetXml.xpath(doc, xpath)
end

The code is vulnerable because it takes a user-provided value (`user_input`) directly to construct an XPath expression. An attacker could exploit this to modify the XPath query and potentially access sensitive information.

Steps

  1. Upgrade to the latest version of Elixir and the sweet_xml library if not done already
  2. Always sanitize user-provided input before using in XPath expressions
  3. Use parameterized queries instead of string concatenation to build XPath expressions

Secure Code Example

def secure(user_input) do
  {:ok, doc} = File.read('data.xml')
  sanitized_input = String.replace(user_input, "'", "''")
  xpath = "//user[username/text() = '" <> sanitized_input <> "']"
  SweetXml.xpath(doc, xpath)
end

This code is safe because it sanitizes the user input by escaping special characters before using it in the XPath expression. It ensures that the user input is treated as literal text, not part of the XPath expression, preventing injection attacks.


References

  • 021 - XPath Injection Vulnerability

  • Last updated

    2023/09/18