Interview Prep/Shell Scripting/ShellCheck, debugging, testing, portability and security

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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on ShellCheck, debugging, testing, portability and security