bashsecuritycode-injectionjavascript-injection

prevent script injection when spawning command line with input arguments from external source


I've got a python script that wraps a bash command line tool, that gets it's variables from external source (environment variables). is there any way to perform some soft of escaping to prevent malicious user from executing bad code in one of those parameters.

for example if the script looks like this

/bin/sh 

/usr/bin/tool ${VAR1} ${VAR2}

and someone set VAR2 as follows

export VAR2=123 && \rm -rf /

so it may not treat VAR2 as pure input, and perform the rm command.

Is there any way to make the variable non-executable and take the string as-is to the command line tool as input ?


Solution

  • The correct and safe way to pass the values of variables VAR1 and VAR2 as arguments to /usr/bin/tool is:

    /usr/bin/tool -- "$VAR1" "$VAR2"