Bash Python3 shlex.quote()安全吗?
我在shell中使用Bash Python3 shlex.quote()安全吗?,bash,python-3.x,security,escaping,Bash,Python 3.x,Security,Escaping,我在shell中使用 subprocess.Popen('echo '+user_string+' | pipe to some string manipulation tools', shell=True) 其中用户字符串来自不受信任的源 使用shlex.quote()转义输入是否足够安全?根据forshlex.quote答案是肯定的 当然,这也取决于你所说的“足够安全”是什么意思。假设您的意思是“在user_string上使用shlex.quote是否会防止恶意shell代码作为字
subprocess.Popen('echo '+user_string+' | pipe to some string manipulation tools',
shell=True)
其中用户字符串来自不受信任的源
使用shlex.quote()
转义输入是否足够安全?根据forshlex.quote
答案是肯定的
当然,这也取决于你所说的“足够安全”是什么意思。假设您的意思是“在
user_string
上使用shlex.quote
是否会防止恶意shell代码作为字符串输入传递到我的脚本中?”答案是肯定的 我之所以对它进行死灵巫术,是因为它是“is shlex.quote()safe”在谷歌上最受欢迎的搜索引擎,虽然公认的答案似乎是正确的,但仍有很多陷阱需要指出
shlex.quote()
将转义shell的解析,但它不会转义您正在调用的命令的参数解析器,并且需要手动执行一些其他特定于工具的转义,特别是当字符串以破折号开头时(-
)
大多数(但不是所有)工具都接受--
作为参数,之后的任何内容都被逐字解释。如果字符串以“-”
开头,则可以在前面加上前缀--“。示例:rm--help
删除名为--help
的文件
处理文件名时,如果字符串以“-”
开头,则可以在前面加上“/”
:rm./--help
在使用echo
的示例中,两种转义都是不够的:当尝试回显字符串-e
时,echo--e
给出错误的结果,您将需要类似echo-e\x2de
的内容。这表明没有通用的防弹方法来逃避程序参数
最安全的方法是绕过shell,方法是避免shell=True
或os.system()
(如果字符串涉及任何用户提供的数据)
在您的情况下,设置stdin=subprocess.PIPE
,并将user\u字符串作为参数传递给communicate()
。然后您甚至可以将原始调用保留为shell=True
:
subprocess.Popen(
'pipe to some string manipulation tools',
shell=True,
stdin=subprocess.PIPE
).communicate(user_input_string.encode())
也许您的代码从一个更复杂的示例中简化了,但是简单地将输入管道化到pipe
在各个方面都优于使用shellecho
引用的表示。