by jcr · 13y ago · 0 comments
'find . -type d -exec chmod g+x {} \;'
If you happen to have a malicious directory named (without double quotes): ".;sudo rm -rf /"
You'd be stuffed.It's better practice to use the '-print0' flag of find(1) and pipe the result into xargs(1) with the '-0' flag set. For safety, it's best to also use '-r #' for expected number of arguments, '-n' to stop xargs from running without arguments, and "-J %" so you can use quoting.
find . -type d -print0 | xargs -0 -n -r 1 -J % chmod g+x "%"
I believe some on implementations '-n' is unnecessary when '-r #' is
specified, but on other implementations it's is the maximum.EDIT: thanks for the vim tip on for finding spelling mistakes!
$ mkdir '; echo woops'
$ find . -type d -exec echo {} ';'
.
./; echo woops
As you can see 'woops' is never echoed.EDIT: The reason being the shell is never involved in this process, and the shell is what is responsible for splitting commands on semicolons/newlines.
FWIW, your `find -print0`/`xargs -0` is not POSIX.
Also, it seems I failed to be clear; I'm probably too tired I suppose.
My point was there is plenty of ancient and buggy code out there. It could be "most", or even "many" modern unix variants have fixed a lot of the old bugs in find(1), but if you don't have the luxury of working on a current system, and your not allowed to upgrade it, then plenty bad things can happen due to invoking a shell, handling space, quote, and delimiter characters, and so forth.
reference:
$ uname -a
OpenBSD alien.foo.test 5.1 GENERIC.MP#207 amd64
setup: $ mkdir test
$ cd test
$ touch file1
$ touch file2
$ touch file3
$ mkdir ';ls'
bad: $ find . -type d -exec sh -c {} \;
sh: ./: cannot execute - Is a directory
;ls file1 file2 file3 test.sh
better: $ find . -type d -exec sh -ec {} \;
sh: ./: cannot execute - Is a directory
also bad: $ find . -type d -print0 | xargs -0 -r -n 1 -J % sh -c "%"
sh: ./: cannot execute - Is a directory
;ls file1 file2 file3 test.sh
better: $ find . -type d -print0 | xargs -0 -r -n 1 -x -J % sh -ec "%"
sh: ./: cannot execute - Is a directory
better; $ find . -type d -print0 | xargs -0 -r -J % sh -c "%"
best: $ find . -type d -print0 | xargs -0 -r -J % sh -ec "%"
POSIX is all great and wonderful in theory, but in practice it's no
different than the bogus Java "write once, run anywhere" claim. If a
system or utility claims to be POSIX compliant, then you're probably
close, but you'll still need to do testing and debugging.At least some of the issues with find/xargs are mentioned in the following wikipedia article. It's probably more clear than I am right now.