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

What are the security rules for scripts that run as root?

AdvancedConceptShellCheck, debugging, testing, portability and security
Answer
  1. Code and config owned by root and not writable by others (install -m 0755 -o root), or anyone can escalate.
  2. Set a known PATH at the top; do not trust the caller's environment (PATH, IFS, LD_PRELOAD, BASH_ENV).
  3. Temp files only via mktemp; never predictable names in /tmp.
  4. Never follow user-controlled symlinks: chown -h, find -P, check with [[ -L ]].
  5. Validate every input; use -- before filenames.
  6. Drop privileges for the parts that do not need root (runuser -u app -- cmd, setpriv).
  7. In sudoers, allow the exact script path with no wildcards in arguments, never an editor or a shell.
All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on ShellCheck, debugging, testing, portability and security