Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

XPath injection

ID: cs/xml/xpath-injectionKind: path-problemSecurity severity: 9.8Severity: errorPrecision: highTags:   - security   - external/cwe/cwe-643Query suites:   - csharp-code-scanning.qls   - csharp-security-extended.qls   - csharp-security-and-quality.qls

Click to see the query in the CodeQL repository

If an XPath expression is built using string concatenation, and the components of the concatenation include user input, a user is likely to be able to create a malicious XPath expression.

Recommendation

If user input must be included in an XPath expression, pre-compile the query and use variable references to include the user input.

When using theSystem.Xml.XPath API, this can be done by creating a custom subtype ofSystem.Xml.Xsl.XsltContext, and implementingResolveVariable(String, String) to return the user provided data. This custom context can be specified for a givenXPathExpression usingXPathExpression.SetContext(). For more details, see the “User Defined Functions and Variables” webpage in the list of references.

Example

In the first example, the code accepts a user name specified by the user, and uses this unvalidated and unsanitized value in an XPath expression. This is vulnerable to the user providing special characters or string sequences that change the meaning of the XPath expression to search for different values.

In the second example, the XPath expression is a hard-coded string that specifies some variables, which are safely replaced at runtime using a customXsltContext that looks up the variables in anXsltArgumentList.

usingSystem;usingSystem.Web;usingSystem.Xml.XPath;publicclassXPathInjectionHandler:IHttpHandler{publicvoidProcessRequest(HttpContextctx){stringuserName=ctx.Request.QueryString["userName"];// BAD: Use user-provided data directly in an XPath expressionstringbadXPathExpr="//users/user[login/text()='"+userName+"']/home_dir/text()";XPathExpression.Compile(badXPathExpr);// GOOD: XPath expression uses variables to refer to parametersstringxpathExpression="//users/user[login/text()=$username]/home_dir/text()";XPathExpressionxpath=XPathExpression.Compile(xpathExpression);// Arguments are provided as a XsltArgumentList()XsltArgumentListvarList=newXsltArgumentList();varList.AddParam("userName",string.Empty,userName);// CustomContext is an application specific class, that looks up variables in the// expression from the varList.CustomContextcontext=newCustomContext(newNameTable(),varList)xpath.SetContext(context);}}

References


[8]ページ先頭

©2009-2025 Movatter.jp