source
is not secure as it will execute arbitrary code. This may not be a concern for you, but if file permissions are incorrect, it may be possible for an attacker with filesystem access to execute code as a privileged user by injecting code into a config file loaded by an otherwise-secured script such as an init script.
So far, the best solution I've been able to identify is the clumsy reinventing-the-wheel solution:
myfile.conf
username=foo
password=bar
echo rm -rf /
PS1=h4xx0r3d
hostname=localhost; echo rm -rf /
Using source
, this would run echo rm -rf /
twice, as well as change the running user's PS1
. Instead, do this:
myscript.sh
#!/bin/bash
typeset -A config # init array
config=( # set default values in config array
[username]="root"
[password]=""
[hostname]="localhost"
)
while read line
do
if echo $line | grep -F = &>/dev/null
then
varname=$(echo "$line" | cut -d '=' -f 1)
config[$varname]=$(echo "$line" | cut -d '=' -f 2-)
fi
done < myscript.conf
echo ${config[username]} # should be loaded from config file
echo ${config[password]} # should be loaded from config file
echo ${config[hostname]} # includes the "injected" code, but in our array it's no threat
echo ${config[PS1]} # also respects variables that you may not have been looking for,
# but they're sandboxed inside the $config array
I hope this helps. Please reply if you find a security exploit in my code.
abcde
also does it this way and that is a quite big program (for a shell script). You can have a look at it here. – Lucas Dec 23 '14 at 21:04