CodeQL 文档

从库输入构建的不安全 shell 命令

ID: py/shell-command-constructed-from-input
Kind: path-problem
Security severity: 6.3
Severity: error
Precision: medium
Tags:
   - correctness
   - security
   - external/cwe/cwe-078
   - external/cwe/cwe-088
   - external/cwe/cwe-073
Query suites:
   - python-security-extended.qls
   - python-security-and-quality.qls

点击查看 CodeQL 代码库中的查询

使用来自库函数的输入动态构建 shell 命令可能会无意中改变 shell 命令的含义。使用导出函数的客户端可能会使用包含 shell 以特殊方式解释的字符的输入,例如引号和空格。这会导致 shell 命令行为异常,甚至允许恶意用户在系统上执行任意命令。

建议

如果可能,将动态参数作为数组提供给 shell,例如 subprocess.run API,以避免 shell 解释。

或者,如果必须动态构建 shell 命令,则添加代码以确保特殊字符不会意外地改变 shell 命令。

示例

以下示例展示了一个动态构建的 shell 命令,该命令从远程 URL 下载文件。

import os

def download(path): 
    os.system("wget " + path) # NOT OK

但是,如果输入包含空格或其他 shell 以特殊方式解释的特殊字符,则 shell 命令将无法按预期工作。

更糟糕的是,客户端可能会传入用户控制的数据,而不知道输入会被解释为 shell 命令。这可能会让恶意用户提供输入 http://example.org; cat /etc/passwd 以执行命令 cat /etc/passwd

为了避免这种潜在的灾难性行为,请将来自库函数的输入作为不会被 shell 解释的参数提供。

import subprocess

def download(path): 
    subprocess.run(["wget", path]) # OK

参考文献

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