【发布时间】:2018-10-14 00:50:00
【问题描述】:
好的,我有一些命令必须在 shell=True 模式下执行。
os.system 或 subprocess.Popen(..., shell=True)
此命令包含字符串替换,例如:cmd = "some_secret_command {0}".format(string_from_user)
我想转义 string_from_user 变量以防止任何注入。
简单的错误答案:
- 使用
shlex.quote- 不正确
print(shlex.quote('file.txxt; &ls . #')) -> 'file.txxt; &ls . #'(注入)
例子:
> python -c "import sys; print(sys.argv[1])" 'file.txxt; &ls . #'
secret.txt
secret2.txt
-
使用转义
^- 不正确
例子:
import os
CMD = '''string with spaces'''.replace('', '^').replace('^"', '')
os.system('python -c "import sys; print(sys.argv[1])" {0}'.format(CMD))
现在我可以使用(空格)并注入多个参数。
- 使用
^和"或'- 不正确
例子:
import os
CMD = '''some arg with spaces'''.replace('', '^').replace('^"', '')
os.system('python -c "import sys; print(sys.argv[1])" "{0}"'.format(CMD))
打印^s^o^m^e^ ^a^r^g^ ^w^i^t^h^ ^s^p^a^c^e^s^
如果'
import os
CMD = '''some spaces'''.replace('', '^').replace('^\'', '')
os.system('python -c "import sys; print(sys.argv[1])" \'{0}\''.format(CMD))
打印'some
我现在知道shell=False,但这对我来说是不正确的。
【问题讨论】:
-
你有 Windows 标签,你能确认你打算运行哪个 shell,例如cmd.exe?我问的原因是因为所需的引用不同,例如 Powershell 使用反引号。
-
我的错,我的意思是
cmd.exe。 -
为什么需要外壳?我不知道你为什么会需要一个。