Thursday, May 3, 2012

XPATH Injection .net

Just like Sql Injection. Xpath injection is a type of attack where hacker can overtake the authentication of the site and try to inject melisious

XPath which may reveal the whole XML and hence display all the required values without proper authentication. Possible solution of these kind of attacks. 1. Validating the Input. 2. Modifying the XPath quite similar to the Sql Parameterized queries so, that changes of hacking it with wrong input will be minimised.


.NET has everything for doing XPath selections that way. But unfortunately the XsltContext API isn't really intuitive one and is poorly documented. Happily there are XML MVPs around :). So Daniel Cazzulino has created handy DynamicContext class, which you can find in recently released Mvp.Xml v1.0 library, particulary in theMvp.Xml.Common.XPath namespace. Read excellent Daniel's explanation for more info. I only want to show you couple of lines that leverage that class. Instead of crappy"//customer[@name='" + txtUser.Text + "' and @password='" + txtPassword.Text + "']" you can have shiny clear "//customer[@name=$name and @password=$password]", precompiled and bulletproof!
//Can be done at initialization time 
string xpath = "//customer[@name=$name and @password=$password]";
XPathExpression expr = DynamicContext.Compile(xpath);

//Run-time
DynamicContext ctx = new DynamicContext();
ctx.AddVariable("name", txtUser.Text);
ctx.AddVariable("password",txtPasowrd.Text);
expr.SetContext(ctx);
XPathNodeIterator custData = customers.Select(expr);
And you don't even have to validate user input here - it's all done for free.
Go download Mvp.Xml and start to play with its classes, there are some gems there that can save you hours of coding and make your code faster and safer. And be aware of XPath injection attack and ways to mitigate it in .NET.
Update from Daniel Cazzulino:
Better yet, they can directly use the XPathCache class (1 line of code!!!):
XPathNodeIterator custData = XPathCache.Select(
    "//customer[@name=$name and @password=$password]",
    customersDocument,
    new XPathVariable("name", txtName.Text), 
    new XPathVariable("password", txtPassword.Text));
And all will be equally precompiled, cached and secure :) . There is an overload for each need, and you can do pretty anything with a single line.

No comments:

Post a Comment