From ac167674b6bc722b85770be50d0be946dac7de05 Mon Sep 17 00:00:00 2001 From: koalaman Date: Sat, 22 Nov 2014 11:59:42 -0800 Subject: [PATCH] Created SC2150 (markdown) --- SC2150.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 SC2150.md diff --git a/SC2150.md b/SC2150.md new file mode 100644 index 0000000..00dd5d5 --- /dev/null +++ b/SC2150.md @@ -0,0 +1,28 @@ +## -exec does not invoke a shell. Rewrite or use -exec sh -c .. . + +### Problematic code: + + find . -type f -exec 'cat {} | wc -l' \; + +### Correct code: + + find . -type f -exec sh -c 'cat {} | wc -l' \; # Insecure + find . -type f -exec sh -c 'cat "$1" | wc -l' _ {} \; # Secure + +Sometimes the command can also be rewritten to not require `find` to invoke a shell: + + find . -type f -exec wc -l {} \; | cut -d ' ' -f 1 + +### Rationale: + +find `-exec` and `-execdir` uses `execve(2)` style semantics, meaning it expects an executable and zero or more arguments that should be passed to it. + +It does not use `system(3)` style semantics, meaning it does not accept a shell command as a string, to be parsed and evaluated by the system's command interpreter. + +If you want `find` to execute a shell command, you have to specify `sh` (or `bash`) as the executable, `-c` as first argument and your shell command as the second. + +To prevent command injection, the filename can be passed as a separate argument to sh and referenced as a positional parameter. + +### Contraindications + +This warning would trigger falsely if executing a program with spaces in the path, if no other arguments were specified. \ No newline at end of file