Run bash-command via subprocess in python without bandit Warning B404 and B603
Asked Answered
H

1

6

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.

bandit-lintings

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)
Hive answered 25/2, 2022 at 9:2 Comment(1)
Note: Instead of starting a aws CLI subprocess causing the bandit warning, you could instead use the (boto3 python library)[https://mcmap.net/q/300158/-how-to-copy-s3-object-from-one-bucket-to-another-using-python-boto3] to do the same S3 Copy operationTourism
T
3

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.)

Tourism answered 26/4, 2023 at 16:14 Comment(2)
Okay, so there is no better way. Just evaluate for oneself, if the input arguments are secure, then add the # nosec - comment to silence the warning?Hive
@AndreasL. Exactly, starting a subprocess is inherently risky, do you need to tell bandit you checked the args are safe.Tourism

© 2022 - 2024 — McMap. All rights reserved.