Prevent Command Injection in Python with Array-Based Arguments

This title was summarized by AI from the post below.

Python has at least eight(?!) ways to execute system commands, and most of them are injectable if you pass user input. We maintain a command injection cheat sheet that covers the common patterns and their fixes. A few highlights: Vulnerable: subprocess.call("grep -R {} .".format(user_input), shell=True) os.system("grep -R {} .".format(user_input)) Safe: subprocess.run(["grep", "-R", user_input, "."]) The fix is almost always the same: use array-based arguments instead of string formatting, and keep `shell=False` (which is the default). When you pass an array, each element becomes a separate argument. The shell never interprets the input, so injection is structurally impossible. Semgrep has pre-built rules for all of these: - python.lang.security.audit.dangerous-subprocess-use - python.lang.security.audit.subprocess-shell-true - python.lang.security.audit.dangerous-system-call Run semgrep --config "p/python" on your codebase and these rules are included. Or browse the full cheat sheet at https://lnkd.in/gYRS2SyS to see all the patterns covered for Python, Java, JavaScript, Go, and Ruby. #SAST #AppSec

To view or add a comment, sign in

Explore content categories