Linux – Best Method to Create Temporary Named Pipe with mktemp

linuxpipeSecurityshell

I'm aware its best to create temporary files with mktemp, but what about named pipes?

I prefer things to be as POSIX compliant as possible, but Linux only is acceptable. Avoiding Bashisms is my only hard criteria, as I write in dash.

Best Answer

tmppipe=$(mktemp -u)
mkfifo -m 600 "$tmppipe"

Unlike regular file creation, which is prone to being hijacked by an existing file or a symbolic link, the creation of a name pipe through mkfifo or the underlying function either creates a new file in the specified place or fails. Something like : >foo is unsafe because if the attacker can predict the output of mktemp then the attacker can create the target file for himself. But mkfifo foo would fail in such a scenario.

If you need full POSIX portability, mkfifo -m 600 /tmp/myfifo is safe against hijacking but prone to a denial of service; without access to a strong random file name generator, you would need to manage retry attempts.

If you don't care for the subtle security problems around temporary files, you can follow a simple rule: create a private directory, and keep everything in there.

tmpdir=
cleanup () {
  trap - EXIT
  if [ -n "$tmpdir" ] ; then rm -rf "$tmpdir"; fi
  if [ -n "$1" ]; then trap - $1; kill -$1 $$; fi
}
tmpdir=$(mktemp -d)
trap 'cleanup' EXIT
trap 'cleanup HUP' HUP
trap 'cleanup TERM' TERM
trap 'cleanup INT' INT
mkfifo "$tmpdir/pipe"
Related Question