Open In App

XPath Injection

Last Updated : 11 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Injection attacks are the most well-known attacks used by hackers to inject code or malware into programs or to query a computer to run remote commands that can read or modify a database or modify data on a website. XPath is a query language that helps by providing relative information on how to find certain elements, such as attributes in an XML document. XPath’s injection is an attack used by hackers to exploit applications that build XPath queries from user input to a browser (navigate) XML document.

Working:

Assume the following is the XML code for a university website that stores student information such as name, username, course, and password. As well as the username, course, and password required to log in to the site.

XML




<?xml version="1.0" encoding="utf-8"?>
<Students>
 <student ID="1">
   <Name>Yashvardhan Choudhary</Name>
   <UserName>BETN1CS221023</UserName>
   <Course>B.Tech CSE</Course>
   <Password>I love GeeksForGeeks</Password>
 </student>
 <student ID="2">
   <Name>Aditya Saxena</Name>
   <UserName>BETN1CS221142</UserName>
   <Course>B.Tech CSE</Course>
   <Password>I love GeeksForGeeks 3000</Password>
 </student>
</Students>


In the XML code above, you can see the username, course, and password required to log in to the website. So the XPath query generated to query the data would look like this:

//"Student[UserName/text()='" & Request("UserName")& "' And 
Course/text()='" & Request("Course")& "' And 
Password/text()='" & Request("Password") & " ' ]"

With a normal username, course, and password, this XPath works, but hackers can send fake username, course, and password and select XML nodes without knowing the username or password, like this:

Username: Geeks or 1=1 or 'a'='a'
Course: Geeks
Password: Geeks
XPath Query:
//Student[UserName/text()='Geeks' or 1=1 or 'a'='a' And 
Course/text()='Geeks' And Password/text()='Geeks']
       
This is equivalent to:
//Student[(UserName/text()='Geeks' or 1=1 or 'a'='a') And 
(Course/text()='Geeks') And (Password/text()='Geeks')]

In this case, just the first part of the XPath is true. The password and course parts become irrelevant, the “username” part matches all students because of the “1=1” part.

Preventive Measure:

  • To protect user input such as username, course, and password, we need to replace the quote (‘) character in the user input with the XML encoded version of that character, giving us “‘.
  • Another better option is to use both parameterized query and parameter input, because for parameter query we have precompiled query, and for parameter input, user input is passed as a parameter instead of expression.

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads