Prevent unauthorized data access through XPath Injection
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.
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.