How to create a temporary file with portable shell in a secure way?
Asked Answered
S

3

13

I want to create a temporary file in POSIX shell (/bin/sh).

I found out that mktemp(1) doens't exist on my AIX box, and according to How portable is mktemp(1)?, it isn't that portable and/or secure anyway.

So, what should I use instead ?

Stoker answered 19/4, 2012 at 9:8 Comment(3)
Well, it isn't a sysadmin question, but a coding one (be it in unix shell).Stoker
What kind of security do you need on this temporary file? That affects what you can use.Elah
@evilotto: well secure mostly means not guessable.Stoker
W
14

Why not use /dev/random?

It could be neater with perl but od and awk will do, something like:

tempfile=XXX-$(od -N4 -tu /dev/random | awk 'NR==1 {print $2} {}')
Woodpecker answered 19/4, 2012 at 19:30 Comment(7)
That's exactly what i was looking for (secure & POSIX). Didn't think about /dev/random, but it feels so obvious once said :)Stoker
For almost all purposes /dev/urandom is preferable. See unix.stackexchange.com/a/324210/197479. Using hex is shorter. Tested this on AIX6.1: tempfile=XXX-$(od -N4 -tx /dev/urandom | awk 'NR==1 {print $2} {}')Asphyxiate
The pipe to awk can be avoided altogether as -An is portable: tempfile=$(od -An -N4 -tx /dev/urandom); tempfile=XXX-${tempfile## }Tenedos
Also, to convert an arbitrary number of bytes one can do: length=7; tempfile=XXX-$(od -An -N${LENGTH} -tx1 /dev/urandom | tr -d ' ')Tenedos
I don't think /dev/random is specified by POSIX.Bartle
You can also use regular expressions to retrieve just the hexa digits: [[ $rnd =~ ([[:xdigit:]]+) ]] && rnd=${BASH_REMATCH[1]}Tussock
tempfile=$(od -An -N4 -tx /dev/urandom | tr -C -d '[:xdigit:]') remove all except hex digits.Tussock
C
3

You didn't exactly define "secure", but one element of it is probably to clean up after yourself.

trap "rm -f \"$tmpfile\"" 0 1 2 3 15

You can probably man 3 signal to see if there are other signals that should cause your temp file to be erased. Signal zero means "on a clean exit".

Counterclaim answered 23/4, 2012 at 12:10 Comment(0)
W
1

Got here from google for portable mktemp. My needs are less secure than OP's, so I ended up just using the script's PID:

tempx=/tmp/mytemp.$$
Wilbourn answered 3/1, 2018 at 3:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.