Can code injection be done using eval in this code?

489 Views Asked by At

This is my first time using bash and I know that eval have some risks when using it. Can you do a code injection to this ? For example I want to run ls command and see the files.

#!/bin/bash
echo "[*] Please enter the name:"
echo -n "> "
read NAME
echo "[*] Please enter the value:"
echo -n "> "
read VALUE
declare CONFIG_$NAME=$VALUE
for VARIABLE in $(compgen -v CONFIG_)
do
   echo "- $VARIABLE: $(eval echo \$$VARIABLE)"
done
3

There are 3 best solutions below

4
Barmar On

If $VARIABLE contains ; the command after it will be executed

VARIABLE=';ls'
echo "- $VARIABLE: $(eval echo \$$VARIABLE)"

The command executed by eval is

echo $;ls

Since $ isn't followed by an identifier, it's simply echoed literally. Then ls is executed.

You could also put a valid identifier at the beginning:

foo=123
VARIABLE="foo;ls"

This will execute

echo $foo;ls

so it will echo 123 then the output of ls.

1
Léa Gris On

Alternatively to using eval with Bash 3.2+, you can use indirect variable reference ${!varname}

for variable in $(compgen -v CONFIG_)
do
   echo "- $variable: ${!variable}"
done

With Bash version 4.2+ you can do the same with nameref variables declare -n var:

for variable in $(compgen -v CONFIG_)
do
  declare -n value=$variable
  echo "- $variable: $value"
done
0
that other guy On

I believe this particular use of eval is safe as it only ever operates on valid identifiers, or alternatively, requires a level of control over the execution that makes the exploit itself moot.

As an attacker, I would have ignored the eval and used one of the other entry points instead, e.g.

$ ./myscript
[*] Please enter the name:
> [`date>&2`]
[*] Please enter the value:
> foo
Thu 05 Nov 2020 04:00:37 PM PST
- CONFIG_: foo