Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Subprocess Security

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?

like image 671
user3175543 Avatar asked Jan 09 '14 00:01

user3175543


People also ask

Is subprocess thread safe Python?

subprocess. Process class is not thread safe. The Concurrency and multithreading in asyncio section.

Should I use subprocess in Python?

Using subprocesses in Python, you can also obtain exit codes and input, output, or error streams. The Subprocess in Python can be useful if you've ever intended to streamline your command-line scripting or utilize Python alongside command-line apps—or any applications, for that matter.

How can we avoid shell true in subprocess?

From the docs: args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names).

What is Popen Python?

Python method popen() opens a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. The bufsize argument has the same meaning as in open() function.


1 Answers

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'])
like image 138
unutbu Avatar answered Oct 04 '22 00:10

unutbu