If $1
contains untrusted user input for example $(whoami)
. Are any of the following bash examples vulnerable to command injection?
I'm having issues clearly understanding this behavior in Bash. Also, I have issues with echo -n "$1"
and echo "$1"
as I think both essentially firstly pass the unsafe contents through a double quoted echo ""
which could expand the command injection I think.
# Example 1: Unsafe?
# Passed unsafe input directly into double quoted echo "" on printf line 1
printf "some text printed between single quotes '%s'" "$(echo -n "$1" | base64 -w0 )"
# Example 2: Unsafe?
# Passed unsafe input directly into double quots echo "" on sanitized line 1
sanitized=$(echo "$1" | sed 's/[$`\\]//g')
printf "some text printed between single quotes '%s'" "$(echo -n "$sanitized" | base64 -w0 )"
# Example 3: Safe?
# Replaced dangerous characters using sed before being passed into double quoted echo ""
sanitized=$(sed 's/[$`\\]//g' <<< $1)
printf "some text printed between single quotes '%s'" "$(echo -n "$sanitized" | base64 -w0 )"
Also, how to fix this if the user input is untrusted, while not stripping any characters (like in the second example) but being safe from command injection.
Or, are all of these examples safe from command injection as long as eval
is not involved in this? If not vulnerable to command injection, are there other risks in this context I should be aware of when the user input is untrusted?
echo -n
instead ofprintf %s
. Test-e
as the input.bash -c 'echo "$1"' - '$(whoami)'