What is the `IFS`/`PATH` hijack risk for setuid-like or sudo scripts, and how do you defend?
AdvancedConceptShellCheck, debugging, testing, portability and security
Answer
If a privileged script inherits the caller's environment, an attacker can set PATH=/tmp/evil:$PATH so ls or tar resolves to their binary, or set BASH_ENV so Bash sources their file on start. Linux ignores setuid on scripts, but sudo rules and root cron jobs that call scripts are the real risk.
#!/usr/bin/env bash
set -Eeuo pipefail
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
unset BASH_ENV ENV CDPATH
IFS=$' \t\n'
umask 027
sudo with env_reset and secure_path (the defaults on most distros) mitigates this; do not add SETENV or env_keep for such scripts. Note that #!/usr/bin/env bash itself uses PATH, so privileged entry points can use #!/bin/bash.
More on ShellCheck, debugging, testing, portability and security
What is ShellCheck and how do you use it in a team?BeginnerHow do you disable a ShellCheck warning, and when is that acceptable?IntermediateName the ShellCheck warnings you see most and what each means.IntermediateHow do you debug a Bash script?BeginnerHow do you make `set -x` output more useful with `PS4`?IntermediateWhat is bats, and how do you test a script that calls external commands?Intermediate