Python: A Guide to Avoiding Command Line Argument Vulnerabilities

In the general scenario, when using a program that parses its command line with a specific technique, such as using X, you can follow the methods explained by Daniel Colascione in his article “Everyone quotes command line arguments the wrong way” to deal with the issue. To resolve this problem, he suggests the first solution where you need to be careful while quoting command lines in Windows as it can affect two parsing engines.


Solution:

Pass a list to subprocess eg

p = subprocess.run(["command", "arg1", "arg2" , f],
                   capture_output=True, text=True)

An announcement pertaining to the Windows system has been made.

Opting for an absolute path to the anticipated binary typically proves to be the most effective strategy. This involves modifying the command to:

p = subprocess.run(["C:\path\to\binary.exe", "arg1", "arg2" , f],
                   capture_output=True, text=True)

In case the complete file path is not familiar, you can utilize

which

to locate your binary. I have tested this method on Windows 7 and newer versions of the operating system.

>>> p = subprocess.run(["which", "python"], stdout=subprocess.PIPE)
>>> python_binary = p.stdout.strip().decode()  # Convert back to str
>>> python_binary
'C:\Program Files\Python36\python.exe'

Frequently Asked Questions