XPath injection

XPath injection in C#

Description

XPath injection occurs when untrusted strings are interpreted as query syntax rather than data. Quotes, logical or path operators and functions can alter predicates or select nodes the application did not intend to expose.

XPathExpression.Compile parses an expression in advance; it does not establish trust. Compiling and reusing an expression built from user input remains unsafe. XmlNamespaceManager resolves namespace prefixes but does not bind query variables.

This differs from XML injection, which changes markup structure, and XXE, which uses external entities to access files or network resources.

Potential impact

  • Authentication or authorization conditions may be bypassed.
  • XML nodes and attributes outside the permitted scope may be disclosed.
  • Errors and repeated queries can reveal the XML structure and its data.
  • Complex attacker-controlled expressions can increase CPU use or response time.

Remediation

  • For a text value, bind a variable in a fixed XPath expression. Implement XsltContext and IXsltContextVariable and pass the context to XPathExpression.SetContext.
  • For a number, check the format and allowed range. Use the normalized number only in a numeric position.
  • For a choice of queries, map each allowed ID to a fixed expression. If you must accept a complete expression, require an exact match in a small set of local literals. Restrict who can change that set.

XML/HTML encoding, SecurityElement.Escape and replacing quotes do not bind XPath values. XmlNamespaceManager resolves prefixes. A helper named Sanitize alone cannot make a string, name or path safe to insert.

Examples

Before

csharp
using Microsoft.AspNetCore.Mvc;
using System.Xml;

XmlNode? FindUser(XmlDocument document, [FromQuery] string name)
{
    var expression = "//users/user[@name='" + name + "']";
    return document.SelectSingleNode(expression);
}

The first query inserts name into the expression itself.

After

Bind string values as variables

The expression passed to XPathExpression.Compile is fixed. The custom XsltContext supplies only the value of $name.

csharp
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

sealed class VariableContext : XsltContext
{
    private readonly IReadOnlyDictionary<string, string> values;

    public VariableContext(
        NameTable nameTable,
        IReadOnlyDictionary<string, string> values) : base(nameTable)
    {
        this.values = values;
    }

    public override bool Whitespace => true;

    public override int CompareDocument(string baseUri, string nextBaseUri) =>
        StringComparer.Ordinal.Compare(baseUri, nextBaseUri);

    public override bool PreserveWhitespace(XPathNavigator node) => true;

    public override IXsltContextFunction ResolveFunction(
        string prefix,
        string name,
        XPathResultType[] argumentTypes) =>
        throw new XPathException($"Unknown function: {prefix}:{name}");

    public override IXsltContextVariable ResolveVariable(
        string prefix,
        string name)
    {
        if (prefix.Length == 0 && values.TryGetValue(name, out var value))
        {
            return new BoundString(value);
        }

        throw new XPathException($"Unknown variable: {prefix}:{name}");
    }
}

sealed class BoundString : IXsltContextVariable
{
    private readonly string value;

    public BoundString(string value) => this.value = value;
    public bool IsLocal => false;
    public bool IsParam => true;
    public XPathResultType VariableType => XPathResultType.String;
    public object Evaluate(XsltContext context) => value;
}

sealed class Search
{
    public XPathNavigator? FindUser(XPathNavigator navigator, [FromQuery] string name)
    {
        var expression = XPathExpression.Compile("//users/user[@name=$name]");
        var values = new Dictionary<string, string> { ["name"] = name };
        expression.SetContext(new VariableContext(new NameTable(), values));
        return navigator.SelectSingleNode(expression);
    }
}

Allow only the variable names and types the query uses, reject unknown variables and functions, and register fixed namespace prefixes when needed.

Parse numeric domains strictly

csharp
using Microsoft.AspNetCore.Mvc;
using System.Globalization;
using System.Xml;

XmlNode? FindUser(XmlDocument document, [FromQuery] string id)
{
    if (!int.TryParse(
            id,
            NumberStyles.None,
            CultureInfo.InvariantCulture,
            out var numericId))
    {
        return null;
    }

    return document.SelectSingleNode($"//users/user[@id={numericId}]");
}

int.TryParse with NumberStyles.None rejects signs and whitespace. Check the application's allowed range before using the parsed int in a numeric comparison.

Map selection tokens to fixed XPath

csharp
using Microsoft.AspNetCore.Mvc;
using System.Xml;

XmlNode? FindView(XmlDocument document, [FromQuery] string view)
{
    string? expression = view switch
    {
        "active" => "//users/user[@active='true']",
        "admin" => "//users/user[@role='admin']",
        _ => null
    };

    return expression is null
        ? null
        : document.SelectSingleNode(expression);
}

Authenticate the caller and check their access to the results. Validate the XML structure and apply XXE protections separately.

Related standards

References