Skip to content
shellhacks.dev
Security

Create a private temp file

Create a private temporary file with mktemp, which gives mode 600 and a random name, and remove it in an EXIT trap even when the script fails.

1 min read
Summarize in AI

A script needs scratch space, and a name like /tmp/job.$$ can be guessed or pre-created by another user.

Shell
cat > job.sh <<'EOF'
tmp=$(mktemp)
trap 'rm -f -- "$tmp"' EXIT
stat -c 'mode %a, owner %U' "$tmp"
echo "work in progress" > "$tmp"
echo "$tmp" > path.txt
exit 3
EOF
bash job.sh; echo "exit: $?"
[ -e "$(cat path.txt)" ] && echo "file left behind" || echo "file removed by the trap"
Text
mode 600, owner root
exit: 3
file removed by the trap

mktemp creates the file itself, with exclusive access and mode 600, and prints the unique random name, which closes the race that a predictable name opens for a symlink attack. The command is described in the coreutils manual. The EXIT trap runs when the shell ends for any reason other than SIGKILL, so the file is removed on success, on exit and after most errors.

A trap does not run when the process receives SIGKILL, or when the machine loses power, so a stale file can remain. Use mktemp -d for a directory and remove it with rm -rf, and set TMPDIR to a private directory for more safety. The demo script exits with status 3 on purpose, and the file is still gone afterwards.

Share

More snippets

Security

Avoid predictable temp names

Never build a temp file name from $$ or a fixed string. An attacker who guesses it can plant a symlink, and mktemp picks an unused random name with mode 600.

1 min read
Security

Avoid eval on input

Never pass input to eval. Run a command held in an array as "${cmd[@]}", or escape a value with printf %q when eval cannot be avoided.

1 min read
Security

Validate input with a whitelist

Validate input against a list of allowed values with a case statement. A grep check with ^ and $ can be fooled by a value that holds a newline.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.