Injection Attacks: The Complete 2020 Guide

XPATH Injections - Defenses

Primary XPATH Defenses

  • Parameterized Queries
  • Escaping user-supplied input

Secondary XPATH Defenses

  • Input Validation

Parameterized Queries

The best security control for preventing injections.

They prevent user-supplied input from changing the purpose of the query.

Regular XPath query...

Username: ' or 1=1 or 'a'='a
Password: gfdjkngdfg

//User[(UserName/text()='' or 1=1) or
    ('a'='a' And Password/text()='gfdjkngdfg')]

X

Parameterized query...

Username: ' or 1=1 or 'a'='a
Password: gfdjkngdfg


XPathNodeIterator userData = XPathCache.Select(
    "//User[@UserName=$username and @Password=$password]",
    userDocument,
    new XPathVariable("username", Username.Text), 
    new XPathVariable("password", Password.Text));

Escaping user-supplied input

If parameterized queries aren't an option, you need to escape all user-supplied inputs before adding them to XPath queries.

Example: if you use single quotes to wrap user inputs, you need to escape quotes in user input.

Input Validation

Input validation can help reject inputs that don't match expectations.

Example: if you are expecting an email address and the input doesn't look like an email, reject it.

XPATH Injection Defenses

By Christophe Limpalair

XPATH Injection Defenses

  • 482