How to create an arbitrary file name for a socket under Linux?

I want to create a small program that uses a local namespace socket, and I will need to use a temporary file name as the address of the socket.

So how to create an arbitrary file name under Linux?

+ I use the C programming language in Debian Linux.
+ According to the GNU C library link, tmpname is not safe. But secure tmpfile and mkstemp create and open the generated file. There are safe and non-create-open there . In other words, the function should prohibit any other request to create the generated file name in a specific directory.

thanks.

+3
source share
4 answers

If you do this in C, use mkdtempto create a directory and put your socket in that directory.

Other functions, such as tmpnamor mktemp, are unsafe; since they do not create or open a temporary file for you, it is easy to be vulnerable to executing a pre-existing symbolic link (placed by an attacker who guessed about your temp file name) in some important file (for example, /etc/passwd), overwriting it.

Note that there is no way to “block” the path - all you can do is create something there. If you need to put the socket in the end, it is best to use the directory as a placeholder.

+6
source

mktemp, GNU coreutils. . manpage.

:

TEMPDIR=$(mktemp -d)
echo $TEMPDIR
touch $TEMPDIR/yourfile.txt

( , .)

+2

, , , C/++ ( - C), tmpnam.

tmpnam, , , , , , , - - . , , tmpnam, , .

tmpfile. (, ) . , , . , .

+1

/dev/random.

google :

</dev/urandom tr -dc A-Za-z0-9 | head -c8

C, /dev/random ( ).

-1

Source: https://habr.com/ru/post/1722295/


All Articles