这还是不受控制的命令行,可以执行恶意代码吗?

问题描述 投票:0回答:1
import os

command = "conda run -n python3.5 python generate_handwriting.py -text '{}' -style {} -bias {} -stroke_color '{}' -stroke_width {} -output '{}'".format(text, style, bias, stroke_color, stroke_width, output_filename)


os.system(command)

我直接从用户那里获取变量,例如

text
。我已收到通知,这可能允许用户执行恶意代码。我已将代码重写为:

import subprocess

cmd = ["conda", "run", "-n", "python3.5", "python", "generate_handwriting.py"]
args = ["-text", str(text), "-style", str(style), "-bias", str(bias), "-stroke_color", str(stroke_color), "-stroke_width", str(stroke_width), "-output", output_filename]

process = subprocess.run(cmd + args, check=True)

问题现在解决了吗?

完整代码可以在这里找到。

python security
1个回答
0
投票

壳注射

subprocess.run
命令与
os.system
不同,默认情况下不允许任意 shell 执行,例如重定向或一个字符串中的多个命令。您必须为此明确设置
shell=True

此外,您将参数放入列表中,这几乎相当于 SQL 准备好的语句的 Python 等价物。

因此,这样做是很多更好。

话虽如此,我仍然建议您按照一般原则使用

shlex.quote
来转义用户输入。例如,假设您要传递一个单字符串命令来运行,而不是命令列表,那么恶意用户可以传递类似
-c "my arbitrary command"
之类的内容。

在您的具体情况下,这不应该成为问题,但安全总比后悔好。

其他问题

如果此进程以比用户更高的权限运行,您还需要确保关闭其他攻击途径。一些明显的例子是:

  • 检查用户是否有权编辑输出目的地。
  • 限制对
    generate_handwriting.py
    的写入访问。
  • 路径中毒,使得
    conda
    可执行文件由用户提供。

但这些都是我的想法,很可能还有更多。

© www.soinside.com 2019 - 2024. All rights reserved.