What are the security rules for scripts that run as root?
AdvancedConceptShellCheck, debugging, testing, portability and security
Answer
- Code and config owned by root and not writable by others (
install -m 0755 -o root), or anyone can escalate. - Set a known
PATHat the top; do not trust the caller's environment (PATH,IFS,LD_PRELOAD,BASH_ENV). - Temp files only via
mktemp; never predictable names in/tmp. - Never follow user-controlled symlinks:
chown -h,find -P, check with[[ -L ]]. - Validate every input; use
--before filenames. - Drop privileges for the parts that do not need root (
runuser -u app -- cmd,setpriv). - In
sudoers, allow the exact script path with no wildcards in arguments, never an editor or a shell.
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