linuxbashshellcode-injection

What are the possible list of Linux bash shell injection commands?


We are writing a Linux bash shell script that receives arguments. We wanted to fail the script when it receives possible shell injections commands as parameters. I have added some commands below using regex. Can someone give me possible list of all such commands so that we can avoid threats

invalid_format="(^.*[;&|].*$)|(\brmdir\b)|(\bls\b)|(rm\s-)|(\bping\b)"

if [[ $LOCAL_DIR =~ $invalid_format ]]; then

echo "Error! LOCAL_DIR cannot contain command chaining characters like ; && || or possible shell injection commands"

exit 1

Solution

  • Don't Use Blocklists.

    A blocklist of content that is explicitly disallowed in your data is just an invitation for someone to come up with a vulnerability that isn't on it, or to obfuscate their code so a regex can't match it, or to find an oddball syntax honored by your actual shell but not by the one the blocklist/validator was written for.

    Don't fight that losing battle; instead, write code that's safe no matter what content your data contains, by never injecting data in a context where it could be evaluated and executed as code.


    Using Arguments In Shell Scripts Safely

    Generating Shell Command Lines Safely

    If forced to use system() or some equivalent

    Generating Safe Command Lines From Another Shell Script

    Let's say you need to run a command with untrusted input over SSH. printf %q can help:

    printf -v args_q '%q ' "$@"
    ssh somehost 'bash -s' <<EOF
    command_with $args_q
    EOF
    

    Why the bash -s? To ensure your args_str is parsed by bash, as printf %q does not guarantee POSIX-safe output.

    But The Better Option? Don't Invoke Extra Shells.

    Instead of using system() or anything that invokes sh -c, use language-level facilities that directly use the execve() syscall to invoke your script. For example, in Python:

    # BAD/EVIL/INSECURE
    subprocess.Popen('yourscript ' + arg, shell=True)  ## DO NOT EVER DO THIS
    
    # GOOD/SECURE
    subprocess.Popen(['yourscript', arg])              ## DO THIS INSTEAD.
    

    Don't Do Other Unsafe Things