Reputation: 2983
I have the following code to get some translations for an old site (its also like this in some other functionality that have more important information.)
Dim myDoc As New XmlDocument
myDoc.Load(Server.MapPath("\GlobalContent\TranslationXML\TranslationXML.xml"))
Dim translationText As XmlNodeList = myDoc.SelectNodes("Transaltions/language[@code='" + hLang.Value + "']")
The Hlang comes from user input,As you can see this is vulnerable to Xpath injection Attacks.
I'm trying to apply the same thing i do with SQL injection that is the use of parameters, but haven't found how to do it in 2.0
I have tried this tutorial : http://weblogs.asp.net/cazzu/archive/2003/10/07/30888.aspx
But the DynamicContext is just part of a library and i cant use it.
Can anyone guide me about how can i fix this?
Upvotes: 2
Views: 2278
Reputation: 243479
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:
Have your XPath expresion pre-compiled with XPathExpression.Compile().
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.
Upvotes: 1
Reputation: 68
Unfortunately, neither XmlDocument nor XPathDocument offer a good means of compiling XPaths with substitution (similar to a compiled SQL query). So, I recommend a slightly more verbose but secure approach - Use the primary XPath to get a XmlNodeList, and iterate through each node and check the attribute until you find one or more matches:
Sample C# code (I'd write VB but I'm quite rusty):
XmlNodeList nodes = myDoc.SelectNodes("Transaltions/language");
foreach (XmlNode node in nodes) {
XmlElement elem = (XmlElement)node;
if (elem.GetAttribute("code") == hLang.Value) {
//elem is your match
}
}
Upvotes: 1