gpt4 book ai didi

.net - XPath 注入(inject)缓解

转载 作者:行者123 更新时间:2023-12-02 13:44:18 34 4
gpt4 key购买 nike

.NET 中是否有任何预先存在的方法来检测/防止 xpath 注入(inject)攻击?

我可以预见 2 个例子,但可能还有更多。

例如

"/Some/XPath/" + UntrustedNodeName

如果 UntrustedNodeName"DoesNotExist |/Some/Other/XPath" 那么这可能是一次攻击。

"/Some/XPath[" + UntrustedFilter + "]"

如果UntrustedFilter“1 = 1”,那么这也可能是一次攻击。

我并不假设我已经涵盖了这里的所有案例!

我猜测这两种情况需要用不同的逻辑分别进行测试。

对于其他类型的攻击,有编码方法和参数化类来减轻风险。对于 XPath,我找不到类似的东西。

(除了 - 我确实找到了这个:http://www.tkachenko.com/blog/archives/000385.html,但安装程序不起作用)

最佳答案

正如 Michael Kay 所说,正确的方法是使用 XPath 变量,但是使用内置 .NET API 有点棘手。我将在下面提供一个(非常简单的)类的示例,该类允许您定义 XPath 变量。一旦你有了它,你就可以像这样使用它:

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);

这个类还应该与 XmlNode.SelectSingleNode()XPathNavigator.Select()XPathNavigator.SelectSingleNode()XPathNavigator.Evaluate() 以及 XElement 中的 XPath 方法。

这提供了一种将用户提供的数据值合并到 XPath 中的安全方法,但与 Tomalak 的答案一样,它没有解决如何允许用户提供整个 XPath 片段的问题。我认为没有办法确定一段 XPath 客观上是否安全,因此如果您担心这存在安全风险,那么唯一的解决方案就是不这样做。

这是类(class)。如果您想让它处理 namespace 和类似的东西,则需要添加它。

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(); }
}
}

}

关于.net - XPath 注入(inject)缓解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19498192/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com