XPath injection mitigation

后端 未结 3 575
情深已故
情深已故 2020-12-07 02:42

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.

3条回答
  •  孤城傲影
    2020-12-07 03:33

    I think you could do the following.

    • For input that should represent node names, throw out all characters that are invalid in a node name (compare the "names" definition). This can be done via regex.
    • 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.

    • Numbers are easy via a sanity check (float.Parse()) and String.Format().
    • Booleans are relatively easy, insert them either as XPath-native Booleans (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.
    • If you want your users to be able to enter whole sub-expressions... Well. Don't.

提交回复
热议问题