Safe way to eval variable declarations?

Is there a safe way to evaluate variable declarations within a script whether they come from a .conf file, user input, or stdin?

Example .conf file:

server=ftp.xxxx.com
port=21
user="$USER"                 # Hopefully allow this type of substitution
domain="$DOMAIN"
server="$(malicious code)"   #prevent this!

Mike

The only safe way for an open entry point into your code is to state and then test ONLY what you will allow.
Blocking what you will not allow is impossible, logically, because the number of wrong or potentially bad inputs is infinite.

Create a list of what is allowed. Check to see that your entry is in there:
Simple minded example, /etc/passwd is the list of allowed users and has : as a field separator; username is field #1, hence the printf format "%s:"

testvar=$(printf "%s:" $user)
grep -Fq "$testvar" /etc/passwd
[ $? -ne 0 ] && exit 1

I'd suggest not using eval at all, just code your own allowed expansions e.g.:

expand='$RANDOM'
[ ${expand:0:1} = "$" ] && {
   expand=${expand:1}
   expand=${!expand}
}

So here we support $var and not $(command)

1 Like

OK, so I understand what expand=${expand:1} is doing (cannot do anything but manipulate variable in variable substitution), but what does expand=${!expand} do?

Mike

It gets the value of the variable "expand" and treats this as a variable name and the fetches its value.

So

$ t=5
$ x=t
$ y=x
$ echo ${!x}
5
$ echo ${!y}
t 
1 Like