Python 子进程安全 [英] Python Subprocess Security
问题描述
我理解为什么如果您有不受信任的输入,使用shell=True"会带来安全风险.但是,我不明白 'shell=False' 如何避免相同的风险.
I understand why using 'shell=True' can be a security risk if you have untrusted input. However, I don't understand how 'shell=False' avoids the same risks.
大概如果我想允许用户提供他可能输入的输入:var="rm -rf/"
Presumably if I wanted to allow a user to provide an input he might input: var="rm -rf /"
我的代码可能只是:
subprocess.call(var,shell=True) # bad stuff
或者我可能会这样做:
varParts=var.split()
subprocess.call(varParts,shell=False) # also bad, right?
似乎假设一个人不会像我在第二个例子中那样经历处理输入的麻烦,因此这会/不可能发生?
It would seem that the assumption is one wouldn't go through the trouble of processing the input as I did in the second example and therefore this would/could not happen?
推荐答案
使用 shell=False
,args[0]
是要执行的程序,args[1:]
作为参数传递给这个程序.
With shell=False
, the args[0]
is the program to be executed and args[1:]
are passed as arguments to this program.
例如,
subprocess.call(['cat','nonexistent;','rm','-rf'])
调用cat
程序并发送3个字符串'nonexistent;'
,'rm'
,'-rf'
作为 cat
的参数.这是完全安全的,尽管无效,因为 -r
是 cat
的无效选项.
calls the cat
program and sends the 3 strings 'nonexistent;'
,'rm'
,'-rf'
as arguments to cat
. This is perfectly safe, though invalid since -r
is an invalid option to cat
.
但是,任意用户输入仍然可能不安全.例如,如果您允许用户控制要调用的程序,如
However, arbitrary user input could still be unsafe. If, for example, you were to allow the user to control the program to be called, as in
subprocess.call(['rm','-rf'])
这篇关于Python 子进程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!