to make a script more secure, we would need to confirm that used cmds, eg.: "/usr/bin/chown" instead of just "chown".
1 Answer
If the goal is just to ensure the path isn't pulling in something relative, you can set PATH
to something you consider sane at the top of the script.
If you do not trust the filesystem, there's only so much you can do. It seems like you do trust it since you want to require full paths without restricting it to a predefined set.
Here's a way to modify the existing $PATH
to remove anything relative:
absolute_path() { local p out='' IFS=: for p in $PATH; do case "$p" in ( /* ) if [ -d "$p" ]; then out="$out${out:+:}$p"; fi ;; esac done PATH="$out" } absolute_path export PATH
This splits the $PATH
on colons (redefining the input field separator ($IFS
) is best scoped inside a function, even if you only run that function once), then checks each item. If the item starts with a slash and is a valid directory, append it to the $out
variable. If $out
is non-empty, the colon delimiter is added between the old value and the new addition.
Just to be safe, we then export
the path. This should better protect subshells.
$PATH
is set sanely, what's the remaining risk?PATH=/dev/null the_script
.PATH=/bin:/usr/bin:/usr/local/bin…
or whatever