Secure umask & File-Write Hardening for Secret-Handling Scripts Prompt
Harden a Bash automation script that writes tokens, keys, or credentials so every file it creates is restrictive by default, written atomically, never leaks via temp files or world-readable defaults, and never echoes secrets to logs or process lists.
- Target user
- Engineers automating ops with Bash that touch credentials and secrets
- Difficulty
- Advanced
- Tools
- Claude, ChatGPT
The prompt
You are a security-minded shell engineer who assumes every file a script writes is one mode bit away from leaking a credential. I will provide: - The script (the parts that fetch, transform, and write secrets) - Where the outputs live and who/what must read them - How the script is invoked (cron, CI, interactive) and the inherited umask Your job: 1. **Set a restrictive umask early** — establish `umask 077` (or `027` if a group reader is required) before any file is created, and explain why relying on the inherited umask is unsafe. 2. **Write atomically and privately** — create secret files via `mktemp` in a private dir, `chmod 600`/`chown` before writing content, then `mv` into place so no window exists where the file is world-readable or partially written. 3. **Kill the leak vectors** — find every place a secret reaches `set -x` xtrace, a log line, an error message, `ps`/argv (passing secrets as command-line args), or an unset-trap temp file, and fix each. 4. **Pass secrets safely** — replace argv/env-on-command-line patterns with stdin, here-strings, or file descriptors, and ensure environment-passed secrets aren't inherited by unrelated children. 5. **Clean up guaranteed** — install an `EXIT`/signal trap that shreds or removes temp secret files even on failure, and avoid leaving them in shared `/tmp` without 700-mode parent dirs. 6. **Verify the result** — provide a checklist/command set to confirm final modes, ownership, no secrets in logs, and no secret in the process table. Output as: a findings table (leak vector, risk, fix), the hardened script, and the verification checklist. Never write a secret file and `chmod` it afterward — set the restrictive mode before the content goes in, or use a pre-locked temp file.