XPath Injection Vulnerability - Elixir

XPath Injection Vulnerability - Elixir

Need

Prevent unauthorized data access through XPath Injection

Context

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

Description

Non compliant code

        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

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

Compliant code

        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