Handling Secrets and Credentials in Scripts
A secret is any value that grants access: a password, an API token, a database connection string with a password in it, a private key, a cloud access key or a session cookie. Automation scripts need secrets all the time, to call APIs, log in to databases, push to registries or copy files to servers.
Handling a secret well means two things. First, the secret must reach the program that needs it. Second, it must reach only that program: not the script file, not the Git history, not the process list, not a log, not a trace, not the shell history and not a temporary file that other users can read. Each of these places is a real and common way that credentials leak.
This lesson shows where secrets leak from Bash scripts, demonstrates each leak, and then shows the techniques that keep a secret on its narrow path.
Understanding the Concept
A Bash script can obtain and pass a secret in several ways. They differ in who else can see it:
| How the secret travels | Who can see it |
|---|---|
| Written in the script | Everyone who can read the script or its repository history |
| Command-line argument | Every user on the machine, through ps and /proc/PID/cmdline |
| Exported environment variable | The same user and root, through /proc/PID/environ; also every child process |
Shell trace (set -x), logs, error messages | Whoever reads the terminal output or the log files |
| Temporary file with default permissions | Often every user on the machine |
| Standard input or a pipe from a built-in | Only the receiving process |
A file with mode 600 | Only the owner (and root) |
The safest paths are at the bottom of the table: a private file that the script reads, and standard input to pass the secret to the next program. The rest of this lesson explains why.
Leak 1: Secrets in the Script or Repository
A line such as API_TOKEN='s3cr3t-abc123' in a script is the most common leak of all. The script gets copied, shared, attached to tickets and committed to Git. Once a secret is committed, deleting the line does not remove it: it stays in every earlier commit and every clone.
Keep secrets out of the script and load them at run time from somewhere that is not shared: a private file, a secrets manager or a credential provided by the service manager. If a secret was ever committed, treat it as exposed and revoke and replace it; cleaning the history is not enough, because copies may already exist.
Leak 2: Command-Line Arguments
Every process's argument list is readable by every user on a normal Linux system. The following test starts a process with a token in its arguments, then looks at it as root and as the unprivileged user nobody:
token='s3cr3t-abc123'
bash -c 'sleep 2; : "$1"' _ "--token=$token" &
pid=$!
sleep 0.3
ps -o user=,args= -p "$pid"
setpriv --reuid=nobody --regid=nogroup --clear-groups ps -o args= -p "$pid"
root bash -c sleep 2; : "$1" _ --token=s3cr3t-abc123
bash -c sleep 2; : "$1" _ --token=s3cr3t-abc123
The second line was produced by a different, unprivileged user, and it still shows the token. Any program that runs for even a moment with a secret in its arguments, for example curl -H "Authorization: Bearer $token" or mysql -p"$password", exposes it this way.
The exception is built-in commands. printf, echo and read run inside the current Bash process and do not start a new process, so their arguments never appear in a process list. That is why printf '%s' "$token" | program is safe, while /usr/bin/printf '%s' "$token" | program would not be.
Leak 3: Environment Variables
Environment variables are better than arguments, but they are not private either:
API_TOKEN=$token bash -c 'sleep 2' &
pid2=$!
sleep 0.3
tr '\0' '\n' < /proc/$pid2/environ | grep '^API_TOKEN'
setpriv --reuid=nobody --regid=nogroup --clear-groups cat /proc/$pid2/environ
ls -l /proc/$pid2/environ
API_TOKEN=s3cr3t-abc123
cat: /proc/588/environ: Permission denied
-r-------- 1 root root 0 Nov 24 09:01 /proc/588/environ
Other users cannot read a process's environment, but the same user and root can. The bigger problem is inheritance: an exported variable is copied into every child process, including programs that log their environment when they crash, debugging tools and third-party scripts:
export DB_PASS=hunter2
bash -c 'echo "child sees: ${DB_PASS-unset}"'
unset DB_PASS
SECRET=only-for-this bash -c 'echo "child sees: $SECRET"'
echo "parent: ${SECRET-unset}"
child sees: hunter2
child sees: only-for-this
parent: unset
When a program can only take a secret from the environment, use the NAME=value command form shown on the second line. It sets the variable for that one command, without exporting it to everything else the script runs. Never export a secret for the whole script.
Leak 4: Traces, Logs and Error Messages
set -x (lesson 126) prints every command after expansion, so it prints secrets too:
( set -x; curl_pw=$token; echo "using it" )
+ curl_pw=s3cr3t-abc123
+ echo 'using it'
using it
Traces are often switched on while debugging and then pasted into tickets or chat. In scripts that handle secrets, run set +x at the start, or wrap the lines that touch the secret in set +x ... set -x. The same care applies to logs and error messages: never print a secret, even partly, except as a short masked suffix such as ****c123 that helps identify which token was used.
Interactive shells have one more trap: commands typed at the prompt are saved to ~/.bash_history. Avoid typing secrets as part of a command. On systems where HISTCONTROL includes ignorespace (Ubuntu's default .bashrc sets ignoreboth), a command that starts with a space is not saved, but a hidden prompt is the better habit.
Leak 5: Files with Default Permissions
New files get their permissions from the umask (lesson 72). With the common umask 022, new files are readable by everyone. A script that writes a token, a downloaded credential or an API response containing personal data must create its files privately. umask 077 makes every file the script creates readable only by its owner:
umask 077; f=$(mktemp); stat -c '%a %n' "$f"
600 /tmp/tmp.W854siv6yr
The same check works the other way round: before reading a secret from a file, confirm that nobody else can read or change it. The permission bits for "group" and "others" are the last two octal digits, so the test is whether mode & 077 is zero:
printf 'x\n' > token.txt; chmod 644 token.txt
perm=$(stat -c '%a' token.txt); (( 8#$perm & 8#077 )) && echo "too open: $perm"
chmod 600 token.txt
perm=$(stat -c '%a' token.txt); (( 8#$perm & 8#077 )) || echo "ok: $perm"
too open: 644
ok: 600
8# tells Bash that the digits are octal. SSH applies the same rule to private keys and refuses keys that others can read.
Getting the Secret into the Script
Reading from a Private File
A file in the user's configuration folder, with mode 600, is simple and works everywhere. Read only the first line, exactly as it is:
IFS= read -r token < "$token_file"
read is a built-in, so the token never appears in a process list, and unlike token=$(cat "$token_file") no extra process is started.
Prompting Without Showing the Input
When a person runs the script, read -s reads without echoing the typed characters:
IFS= read -rs -p 'Password: ' pw; echo >&2
-s turns off echo only when standard input is a terminal. -p likewise shows its prompt only on a terminal. The echo >&2 moves to a new line after the hidden input. Check [[ -t 0 ]] before prompting, so the script fails clearly instead of waiting when it runs without a terminal, for example from cron.
Credentials from the Service Manager
When a script runs as a systemd service, the unit can provide credentials with LoadCredential=name:/path or SetCredentialEncrypted=. systemd places them in a private folder whose path is in the environment variable CREDENTIALS_DIRECTORY, readable only by the service. The script then reads $CREDENTIALS_DIRECTORY/name. Secret managers such as HashiCorp Vault, cloud secret services, pass or the CI system's secret store work in a similar way: the script asks for the secret at run time and never stores it.
Passing the Secret On
The last step is handing the secret to the program that uses it, without putting it in that program's arguments. Many tools have a way to read secrets from standard input or from a file:
| Tool | Safe way |
|---|---|
curl | -H @- (headers from stdin), -K - (config from stdin), --netrc-file FILE |
docker login | --password-stdin |
mysql, psql | option files (--defaults-extra-file), ~/.pgpass, or the MYSQL_PWD/PGPASSWORD environment variable for that command only |
ssh, git | keys and credential helpers instead of passwords |
gpg, openssl | --passphrase-fd 0, -pass stdin or -pass file: |
The following test uses a small local test server that answers HTTP 200 only when it receives the header Authorization: Bearer s3cr3t-abc123, and 401 otherwise:
url=http://127.0.0.1:8765/items
printf 'header = "Authorization: Bearer %s"\n' "$token" | curl -s --noproxy '*' -K - "$url"
printf 'Authorization: Bearer %s\n' "$token" | curl -s --noproxy '*' -H @- "$url"
printf 'Authorization: Bearer %s\n' wrong | curl -s --noproxy '*' -o /dev/null -w '%{http_code}\n' -H @- "$url"
(--noproxy '*' only stops curl from sending these local test requests through a proxy server.)
{"path": "/items", "authorized": true}
{"path": "/items", "authorized": true}
401
In both successful forms, the token travelled from the built-in printf through a pipe into curl. It was never part of any argument list.
When the secret is no longer needed, unset token removes it from the script's memory, so a later function or a debugging session cannot print it by accident.
A Complete Example: Calling an API Without Exposing the Token
api-get.sh fetches one path from an API. It looks for the token in a systemd credentials folder, then in a private file, and finally asks for it at a hidden prompt. It refuses token files that other users could read or change, never traces itself, never puts the token in an argument list or the environment, and shows only the last four characters in its log line.
#!/usr/bin/env bash
# api-get.sh: call an API endpoint without exposing the token
# usage: api-get.sh PATH
# The token is read, in this order, from:
# 1. $CREDENTIALS_DIRECTORY/api_token (systemd LoadCredential=)
# 2. the file named in $API_TOKEN_FILE (default ~/.config/api-get/token)
# 3. a hidden prompt, when standard input is a terminal
set -uo pipefail
umask 077 # any file we create is private
set +x # never trace this script
base_url=${API_URL:-http://127.0.0.1:8765}
token_file=${API_TOKEN_FILE:-$HOME/.config/api-get/token}
die() { printf '%s: %s\n' "${0##*/}" "$1" >&2; exit "${2:-1}"; }
# Refuse files that other users can read or change, or that we do not own
check_private_file() {
local file=$1 perm owner
[[ -f $file && ! -L $file ]] || die "not a regular file: ${file@Q}"
read -r perm owner < <(stat -c '%a %u' -- "$file") || die "cannot check ${file@Q}"
(( owner == EUID )) || die "${file@Q} is owned by user $owner, not by you"
(( (8#$perm & 8#077) == 0 )) || die "${file@Q} has mode $perm; run: chmod 600 ${file@Q}"
}
load_token() {
local file
if [[ -n ${CREDENTIALS_DIRECTORY-} && -f $CREDENTIALS_DIRECTORY/api_token ]]; then
file=$CREDENTIALS_DIRECTORY/api_token
elif [[ -e $token_file ]]; then
file=$token_file
check_private_file "$file"
elif [[ -t 0 ]]; then
IFS= read -rs -p 'API token: ' token; echo >&2
[[ -n $token ]] || die 'no token entered'
return
else
die "no token: create ${token_file@Q} (mode 600) or run in a terminal"
fi
IFS= read -r token < "$file" || [[ -n ${token-} ]] || die "token file is empty: ${file@Q}"
}
mask() { local s=$1; printf '****%s' "${s: -4}"; }
(( $# == 1 )) || die 'usage: api-get.sh PATH' 2
path=$1
[[ $path =~ ^/[A-Za-z0-9/_.-]*$ ]] || die "invalid path: ${path@Q}" 2
token=
load_token
[[ $token =~ ^[A-Za-z0-9._-]{8,200}$ ]] || die 'token has an unexpected format'
printf 'GET %s (token %s)\n' "$path" "$(mask "$token")" >&2
# The header goes to curl on standard input: printf is a built-in, so the
# token never appears in any process's argument list or environment.
status=$(printf 'Authorization: Bearer %s\n' "$token" |
curl -sS --noproxy '*' -H @- -o response.json -w '%{http_code}' -- "$base_url$path") ||
die 'request failed'
unset token
if [[ $status == 200 ]]; then
cat response.json
else
die "server answered HTTP $status"
fi
How It Works
- Safe defaults first.
umask 077makesresponse.json(which may contain private data) readable only by the owner.set +xswitches tracing off even when someone runsbash -x api-get.sh. - Three token sources. The systemd credentials folder is checked first, because it is the most controlled source. A token file is used next, but only after
check_private_fileconfirms that it is a regular file (not a symbolic link that could point elsewhere), that the current user owns it, and that its mode gives no access to group or others. The hidden prompt is used only when standard input is a terminal; otherwise the script stops with an instruction. - Reading the file.
IFS= read -r token < "$file"reads the first line exactly. The|| [[ -n ${token-} ]]part accepts a file whose only line has no final newline, which is common when a token is pasted into an editor or written withprintf '%s'. - Validation. The path must start with
/and contain only safe URL characters, so it cannot add options or shell syntax. The token must look like a token: a missing line or a pasted line with spaces is reported before anything is sent. - Masking.
${s: -4}takes the last four characters (the space before-4is required, otherwise Bash reads:-as a default value). The log line identifies which token was used without revealing it. - Passing the token. The header is written by the built-in
printfinto a pipe, andcurl -H @-reads it from standard input.--noproxy '*'keeps this local test from going through a proxy; drop it for a real API.-w '%{http_code}'prints only the HTTP status, which the command substitution captures.--endscurl's options before the URL. - Clean-up.
unset tokenremoves the secret as soon as it is no longer needed.
Running the Complete Example
The test server from the previous section is running. The token file is set with API_TOKEN_FILE=token.txt, which does not exist yet, and standard input is not a terminal:
export API_TOKEN_FILE=token.txt
./api-get.sh /items < /dev/null; echo "status $?"
printf 's3cr3t-abc123\n' > token.txt; chmod 644 token.txt
./api-get.sh /items < /dev/null; echo "status $?"
chmod 600 token.txt
./api-get.sh /items < /dev/null; echo "status $?"; stat -c '%a %n' response.json
api-get.sh: no token: create 'token.txt' (mode 600) or run in a terminal
status 1
api-get.sh: 'token.txt' has mode 644; run: chmod 600 'token.txt'
status 1
GET /items (token ****c123)
{"path": "/items", "authorized": true}
status 0
600 response.json
The script refused to wait for a prompt that nobody could answer, refused a token file readable by everyone and told the user how to fix it, then succeeded once the file was private. The response file was created with mode 600 because of the umask.
Other sources and problems are handled as well:
printf 'wrong-token-1\n' > other.token; chmod 600 other.token
API_TOKEN_FILE=other.token ./api-get.sh /items < /dev/null; echo "status $?"
mkdir -p creds; printf 's3cr3t-abc123' > creds/api_token
CREDENTIALS_DIRECTORY=$PWD/creds ./api-get.sh /orders/7 < /dev/null; echo "status $?"
./api-get.sh '/items; rm -rf /' < /dev/null; echo "status $?"
ln -sf other.token link.token
API_TOKEN_FILE=link.token ./api-get.sh /items < /dev/null; echo "status $?"
cp other.token nobody.token; chown nobody nobody.token
API_TOKEN_FILE=nobody.token ./api-get.sh /items < /dev/null; echo "status $?"
GET /items (token ****en-1)
api-get.sh: server answered HTTP 401
status 1
GET /orders/7 (token ****c123)
{"path": "/orders/7", "authorized": true}
status 0
api-get.sh: invalid path: '/items; rm -rf /'
status 2
api-get.sh: not a regular file: 'link.token'
status 1
api-get.sh: 'nobody.token' is owned by user 65534, not by you
status 1
The wrong token was sent and rejected by the server, and the masked suffix shows which token it was. The systemd-style credentials folder worked with a token file that has no final newline. The path with shell syntax, the symbolic link and the file owned by another user were all refused before any request was made. Finally, running the whole script under bash -x and searching the trace for the token finds nothing, because set +x switched tracing off before the token was loaded:
bash -x ./api-get.sh /items < /dev/null 2>&1 | grep -c s3cr3t
0