Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent XPath/XML injection in .NET

How can I prevent XPATH injection in the .NET Framework?

We were previously using string concatenation to build XPATH statements, but found that end users could execute some arbitrary XPATH. For example:

string queryValue = "pages[@url='" + USER_INPUT_VALUE + "']";
node = doc.DocumentElement.SelectSingleNode(queryValue);

Would it be sufficient to strip out single and double quotes from input strings?

Or, does the .NET framework support parameterized XPATH queries?

like image 905
frankadelic Avatar asked Jun 17 '11 05:06

frankadelic


2 Answers

The main idea in preventing an XPath injection is to pre-compile the XPath expression you want to use and to allow variables (parameters) in it, which during the evaluation process will be substituted by user-entered values.

In .NET:

  1. Have your XPath expresion pre-compiled with XPathExpression.Compile().

  2. Use the XPathExpression.SetContext() Method to specify as context an XsltContext object that resolves some specific variables to the user-entered values.

You can read more about how to evaluate an XPath expression that contains variables here.

This text contains good and complete examples.

like image 66
Dimitre Novatchev Avatar answered Sep 19 '22 09:09

Dimitre Novatchev


Strongly typed parameters are available if you use a full-blown XsltTransform.

like image 29
Serguei Avatar answered Sep 19 '22 09:09

Serguei