Since the pre-commit hook does not allow even warnings and commits issued by bandit, I need to find a way to execute bash commands from python scripts without bandit complaining.
Using the subprocess python package, bandit has always complained so far, no matter what I did. I used ".run()", ".check_call()", ".Popen()", .. all without shell=True
and yet there's no avail.
If there is a secure alternative to subprocess, I'd also be interested, but I'm sure it must work somehow with subprocess as well.
Example which is not accepted by bandit:
import shlex
import subprocess
...
bash_command = (
f'aws s3 cp {source_dir} s3://{target_bucket_name} --recursive'
f' --profile {profile_name}')
subprocess.check_call(shlex.split(bash_command), text=True)
In order for the code to be secure, you need to know that source_dir
target_bucket_name
profile_name
aren't malicious: e.g. can an untrusted user pass .ssh
as the value to be copied?
Once you know the subprocess line is secure, you can add # nosec
comment to tell bandit not to give a warning about the line:
subprocess.check_call(shlex.split(bash_command), text=True) # nosec
(The command aws s3 ...
running in subprocess.check_call
isn't running in a bash shell, which might confuse people reading the question. Python will directly start the aws
process, passing arguments.)