Avoid using shell=true in python subprocess module
Using python subprocess module we can execute shell command.
This modules takes some arguments along with an option to set ‘shell=true’
Now the question comes is it safe or recommended to use ‘shell=true’ in subprocess module call which is being use for executing a command.
The use of shell=true is strongly discouraged in cases where the command string is constructed from external input. We should avoid using ‘shell=true’ in subprocess call to avoid shell injection vulnerabilities.
Get Vikash Acharya’s stories in your inbox
Join Medium for free to get updates from this writer.
Let’s understand it through some examples :
def call_method(command_to_be_executed):
output = subprocess.check_output(command_to_be_executed, shell=True)In this call you have to pass a string as a command to the shell.
If call_method is user controlled then it can be used to execute any arbitrary command which can affect system. For example what if command like “rm -rf /” pass to this method as command to execute.
We can set shell=false and reconstruct our method call by passing a list of strings as command rather than passing a complete string to subprcess.
String command = "sudo cat /dirPath/filename"Convert it to - command_to_be_executed = ['sudo', 'cat', '/dirPath/filename']
def call_method(command_to_be_executed):
output = subprocess.check_output(command_to_be_executed, shell=False)







