I am looking for a secure place to put Unix domain sockets that will be used to control a REPL.
On Linux, I would use /run/user/$UID
, which meets all requirements except for portability. I need the program that handles them to be portable.
One option is to use a directory under ~
but that runs into a different problem: the user's home directory might be in a directory too deep to be able to bind a Unix domain socket to, due to the limit in the path length.
Placing the socket in a directory under /tmp
is portable, but I am worried about race conditions upon removing the directory. I am also worried about whether /tmp
can be relied on to have the sticky bit set on all platforms (that is, for users to not be able to delete or rename other user's temporary files). I am assuming that /tmp
IS sticky, however, as otherwise many, many applications (every script that uses mkstemp
) is insecure.
My current plan is for the server to create a temporary directory in /tmp
, and for the clients to check the ownership of the containing directory before using the socket. Is this adequate for security?
Best Answer
The de jure standard location for temporary files is given in the environment variable
TMPDIR
.In fact, many systems do not define
TMPDIR
. The de facto standard location for temporary files is/tmp
. So checkTMPDIR
, and if it is not set, use/tmp
. In a shell script, you can use${TMPDIR:-/tmp}
, or if you find it more convenient,or to cope with
set -u
You can assume that this location is writable, but it may be world-readable and world-writable, so:
mktemp
utility (widespread, present on GNU, BusyBox, BSD, but not POSIX) or themkstemp
C library function. Under the hood,open
orcreat
must be called with theO_EXCL
flag.mkdir
. This is secure against ownership trickery stealing, because that won't reuse an existing file, but it is prone to the same denial of service as regular files, so you should use a random name.mktemp -d
is a fine way to do this.Linux honors permissions on named sockets, but there are Unix variants that don't. This is why sockets in
/tmp
are usually created in subdirectories.Programs that create a subdirectory of
/tmp
(or$TMPDIR
if set) and create a named socket there include X11 servers, ssh-agent, gpg-agent, KDE, emacs, … (that's just the ones that exist on the machine where I'm posting this). As you can see, you'll be in good company.