XPath injection mitigation

后端 未结 3 529
情深已故
情深已故 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:25

    Just avoid building XPath expressions using string concatenation. Use parameters/variables instead.

    0 讨论(0)
  • 2020-12-07 03:29

    As Michael Kay says, the right approach here is to use XPath variables, but this is a bit tricky using built-in .NET APIs. I'll provide an example below of a (very bare bones) class that allows you to define XPath variables. Once you have that, you can make use of it like this:

    VariableContext context = 
                   new VariableContext { { "hello", 4 }, { "goodbye", "adios" } };
    
    // node is a System.Xml.XmlNode object
    XmlNodeList result = 
                   node.SelectNodes("/my/field[. = $hello or . = $goodbye]", context);
    

    This same class should also work with XmlNode.SelectSingleNode(), XPathNavigator.Select(), XPathNavigator.SelectSingleNode(), XPathNavigator.Evaluate(), and the XPath methods in XElement.

    This provides a safe way to incorporate user-provided data values into your XPath, but as with Tomalak's answer, it does not address the issue of how to allow your user to provide entire pieces of XPath. I don't think there is a way to determine whether a piece of XPath is objectively safe or not, so if you're worried about that being a security risk, then the only solution is to not do it.

    Here is the class. If you want to have it handle namespaces and stuff like that, that would need to be added.

    class VariableContext : XsltContext
    {
        private Dictionary<string, object> m_values;
    
        public VariableContext()
        {
            m_values = new Dictionary<string, object>();
        }
    
        public void Add(string name, object value)
        {
            m_values[name] = value;
        }
    
        public override IXsltContextVariable ResolveVariable(string prefix, string name)
        {
            return new XPathVariable(m_values[name]);
        }
    
        public override int CompareDocument(string baseUri, string nextbaseUri)
        {
            throw new NotImplementedException();
        }
    
        public override bool PreserveWhitespace(XPathNavigator node)
        {
            throw new NotImplementedException();
        }
    
        public override IXsltContextFunction ResolveFunction(string prefix, string name, 
                                                             XPathResultType[] ArgTypes)
        {
            throw new NotImplementedException();
        }
    
        public override bool Whitespace
        {
            get { throw new NotImplementedException(); }
        }
    
        private class XPathVariable : IXsltContextVariable
        {
            private object m_value;
    
            internal XPathVariable(object value)
            {
                m_value = value;
            }
    
            public object Evaluate(XsltContext xsltContext)
            {
                return m_value;
            }
    
            public bool IsLocal
            {
                get { throw new NotImplementedException(); }
            }
    
            public bool IsParam
            {
                get { throw new NotImplementedException(); }
            }
    
            public XPathResultType VariableType
            {
                get { throw new NotImplementedException(); }
            }
        }
    
    }
    
    0 讨论(0)
  • 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.
    0 讨论(0)
提交回复
热议问题