Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash Python3 shlex.quote()安全吗?_Bash_Python 3.x_Security_Escaping - Fatal编程技术网

Bash Python3 shlex.quote()安全吗?

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代码作为字

我在shell中使用

subprocess.Popen('echo '+user_string+' | pipe to some string manipulation tools',
    shell=True)
其中用户字符串来自不受信任的源

使用
shlex.quote()
转义输入是否足够安全?

根据for
shlex.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
在各个方面都优于使用shell
echo
引用的表示。