popen
call with shell equals True
BAN-B602 7 def test(self):
8 """Test the project."""
9 test_command = 'mvn test'
10 subprocess.run(test_command, cwd=self.project_dir, shell=True)
8 def deploy(self):
9 """Deploy the project to the target environment."""
10 deploy_command = f'mvn deploy -Dtarget-env={self.target_env}'
11 subprocess.run(deploy_command, cwd=self.project_dir, shell=True)
7 def build(self):
8 """Build the project."""
9 build_command = 'mvn clean package'
10 subprocess.run(build_command, cwd=self.project_dir, shell=True)
Using shell=True
can expose you to security risks if someone crafts input to issue different commands than the ones you intended.
Python possesses many mechanisms to invoke an external executable. However, doing so may present a security issue if appropriate care is not taken to sanitize any user-provided or variable input. Subprocess invocation using a command shell is dangerous as it is vulnerable to various shell injection attacks. It is possible for an attacker to craft inputs to issue different commands than the ones you intended, for example: removing a file.
Great care should be taken to sanitize all input in order to mitigate this risk. Calls of this type are identified by a parameter of shell=True
being given.
It is recommended to use functions that don't spawn a shell. If you must use them, use shlex.quote
to sanitize the input.
import subprocess
subprocess.Popen(cmd, shell=True) # Sensitive, shell spawned
import subprocess
subprocess.Popen(cmd)