CodeQL 文档

从用户控制的来源构建的 XPath 查询

ID: py/xpath-injection
Kind: path-problem
Security severity: 9.8
Severity: error
Precision: high
Tags:
   - security
   - external/cwe/cwe-643
Query suites:
   - python-code-scanning.qls
   - python-security-extended.qls
   - python-security-and-quality.qls

点击查看 CodeQL 存储库中的查询

如果 XPath 表达式是使用字符串连接构建的,并且连接的组件包含用户输入,则用户很容易创建恶意 XPath 表达式。

建议

如果用户输入必须包含在 XPath 表达式中,请清理数据或使用变量引用来安全地嵌入它,而不会改变表达式的结构。

示例

在下面的示例中,xpath 查询由用户控制,因此会导致漏洞。

from lxml import etree
from io import StringIO

from django.urls import path
from django.http import HttpResponse
from django.template import Template, Context, Engine, engines


def a(request):
    value = request.GET['xpath']
    f = StringIO('<foo><bar></bar></foo>')
    tree = etree.parse(f)
    r = tree.xpath("/tag[@id='%s']" % value)


urlpatterns = [
    path('a', a)
]

这可以通过使用参数化查询来解决,如下所示。

from lxml import etree
from io import StringIO

from django.urls import path
from django.http import HttpResponse
from django.template import Template, Context, Engine, engines


def a(request):
    value = request.GET['xpath']
    f = StringIO('<foo><bar></bar></foo>')
    tree = etree.parse(f)
    r = tree.xpath("/tag[@id=$tagid]", tagid=value)


urlpatterns = [
    path('a', a)
]

参考资料

  • OWASP XPath 注入:/>>

  • 通用弱点枚举:CWE-643.

  • ©GitHub, Inc.
  • 条款
  • 隐私