Are there any pre-existing methods in .NET to detect/prevent an xpath injection attack?
I can forsee 2 examples but there are likely many more.
e.g.
I think you could do the following.
For input that should represent strings it comes in handy that there are no escape sequences in XPath.
Either throw out all single quotes from the user input and only work with single quoted strings in your expression templates. You are safe from injection because there is no way to escape from a single quoted string other than a single quote.
var xpathTmpl = "/this/is/the/expression[@value = '{0}']";
var input = "asd'asd";
var safeInput = input.Replace("'", "");
var xpath = String.Format(xpathTmpl, safeInput);
// -> "/this/is/the/expression[@value = 'asdasd']"
Or the other way around. Same effect, more backslashes (in C# at least).
var xpathTmpl = "/this/is/the/expression[@value = \"{0}\"]";
var input = "asd\"asd";
var safeInput = input.Replace("\"", "");
var xpath = String.Format(xpathTmpl, safeInput);
// -> "/this/is/the/expression[@value = "asdasd"]"
…of course that's not 100% nice because you change the user's input.
If you want to represent the user input verbatim, you must split it into sections at the XPath string delimiter you chose (say, the single quote) and use XPath's concat() function, like this:
var xpathTmpl = "/this/is/the/expression[@value = {0}]";
var input = "asd'asd";
var inputParts = input.Split('\'');
var safeInput = "concat('" + String.Join("', \"'\", '", inputParts) + "')";
var xpath = String.Format(xpathTmpl, safeInput);
// -> "/this/is/the/expression[@value = concat('asd', "'", 'asd')]"
Wrap that in a utility function and dynamic XPath building becomes manageable.
float.Parse()) and String.Format().true() or false()) or as numeric values (i.e. 1 or 0), which are then coerced to Booleans automatically by XPath when used in a Boolean context.