Secure Secret Handling and Environment Hygiene
Keep credentials out of process listings and logs using stdin, files, and scrubbed environments.
Why Secret Hygiene Matters
Secrets — API keys, passwords, tokens — are the most sensitive data in any system. Mishandling them in Bash scripts is one of the most common and damaging security mistakes.
- Process listings: Arguments passed to commands appear in
ps aux,/proc/<pid>/cmdline, and system audit logs — visible to all users on the host. - Shell history: Commands typed interactively (and sometimes scripts) are recorded in
~/.bash_history. - Log files:
set -xtraces, application logs, and CI/CD output can capture variable values. - Environment leakage: Child processes inherit the full environment of their parent, including any exported secrets.
A hardened script treats secrets like radioactive material — minimise exposure time, limit surface area, and sanitise everything on the way out.
The Process Listing Attack Surface
When you pass a secret as a command-line argument, every user on the system can read it immediately via ps. This is not theoretical — it is exploited routinely in shared hosting and container environments.
The snippet below demonstrates the problem and the fix side by side.
#!/usr/bin/env bash
# DANGEROUS: password visible in 'ps aux' output
# curl -u "admin:SuperSecret123" https://api.example.com/data
# SAFE: pass credentials via stdin or a flag that reads from a file
# Many tools support reading secrets from stdin with '-' or dedicated flags:
# Option 1 — pipe the secret so it never appears in argv
echo 'SuperSecret123' | curl -u 'admin' --password-stdin \
https://api.example.com/data 2>/dev/null || true
# Option 2 — write a temporary netrc and point curl at it
# (covered in a later scene)
echo 'Secret never touches the command line this way'All lessons in this course
- Preventing Command and Argument Injection
- Secure Secret Handling and Environment Hygiene
- Least-Privilege Execution and sudo Discipline
- Static Analysis and Auditing with ShellCheck