Python Subprocess Security

只谈情不闲聊 提交于 2021-02-20 06:11:18

问题


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.

Presumably if I wanted to allow a user to provide an input he might input: var="rm -rf /"

My code might simply:

subprocess.call(var,shell=True) # bad stuff

Or I might do:

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?


回答1:


With shell=False, the args[0] is the program to be executed and args[1:] are passed as arguments to this program.

So, for example,

subprocess.call(['cat','nonexistent;','rm','-rf'])

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'])


来源:https://stackoverflow.com/questions/21009416/python-subprocess-security

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!