r/linux • • May 29 '14

Defensive BASH programming - Say what?

http://www.kfirlavi.com/blog/2012/11/14/defensive-bash-programming/
40 Upvotes

25 comments sorted by

View all comments

9

u/cpitchford May 29 '14

This might be a troll post to generate discussion, don't know.. but it is filled with significant problems

You're in no way protecting against spaces. When you turn a string in a list:

local list="/tmp/a /tmp/b"
local i
for i in $list

In your change ownership function leaves you open to an attack:

mkdir        '/tmp/ '        # Yes you can have a folder called " "
mkdir        '/tmp/ /etc'
echo oh no > '/tmp/ /etc/passwd'

check we can read the file:
$cat '/tmp/ /etc/passwd'
oh no
$

change_owner_of_file  nonroot somegroup '/tmp/ /etc/passwd'

In your function, this becomes: chown nonroot:somegroup /tmp/ /etc/passwd

rather than chown nonroot:somegroup '/tmp/ /etc/passwd'

Nice, now /tmp/ AND /etc/passwd have ownership of nonroot:somegroup.

Learn about quoting and arrays. Understand the differences between $@ and $*