Linux create temporary file unique name

Linux create temporary file unique name

If you need to use a temporary file in your program, you can use the tmpfile function to open it. Or you can use the tmpnam (better: tmpnam_r ) function to provide a name for a temporary file and then you can open it in the usual way with fopen .

The tempnam function is like tmpnam but lets you choose what directory temporary files will go in, and something about what their file names will look like. Important for multi-threaded programs is that tempnam is reentrant, while tmpnam is not since it returns a pointer to a static buffer.

These facilities are declared in the header file stdio.h .

Function: FILE * tmpfile (void)

Preliminary: | MT-Safe | AS-Unsafe heap lock | AC-Unsafe mem fd lock | See POSIX Safety Concepts.

This function creates a temporary binary file for update mode, as if by calling fopen with mode «wb+» . The file is deleted automatically when it is closed or when the program terminates. (On some other ISO C systems the file may fail to be deleted if the program terminates abnormally).

This function is reentrant.

When the sources are compiled with _FILE_OFFSET_BITS == 64 on a 32-bit system this function is in fact tmpfile64 , i.e., the LFS interface transparently replaces the old interface.

Function: FILE * tmpfile64 (void)

Preliminary: | MT-Safe | AS-Unsafe heap lock | AC-Unsafe mem fd lock | See POSIX Safety Concepts.

This function is similar to tmpfile , but the stream it returns a pointer to was opened using tmpfile64 . Therefore this stream can be used for files larger than 2^31 bytes on 32-bit machines.

Please note that the return type is still FILE * . There is no special FILE type for the LFS interface.

If the sources are compiled with _FILE_OFFSET_BITS == 64 on a 32 bits machine this function is available under the name tmpfile and so transparently replaces the old interface.

Function: char * tmpnam (char * result )

Preliminary: | MT-Unsafe race:tmpnam/!result | AS-Unsafe | AC-Safe | See POSIX Safety Concepts.

This function constructs and returns a valid file name that does not refer to any existing file. If the result argument is a null pointer, the return value is a pointer to an internal static string, which might be modified by subsequent calls and therefore makes this function non-reentrant. Otherwise, the result argument should be a pointer to an array of at least L_tmpnam characters, and the result is written into that array.

It is possible for tmpnam to fail if you call it too many times without removing previously-created files. This is because the limited length of the temporary file names gives room for only a finite number of different names. If tmpnam fails it returns a null pointer.

Warning: Between the time the pathname is constructed and the file is created another process might have created a file with the same name using tmpnam , leading to a possible security hole. The implementation generates names which can hardly be predicted, but when opening the file you should use the O_EXCL flag. Using tmpfile or mkstemp is a safe way to avoid this problem.

Function: char * tmpnam_r (char * result )

Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.

This function is nearly identical to the tmpnam function, except that if result is a null pointer it returns a null pointer.

This guarantees reentrancy because the non-reentrant situation of tmpnam cannot happen here.

Warning: This function has the same security problems as tmpnam .

Читайте также:  Как отключить защиту windows defender

Macro: int L_tmpnam

The value of this macro is an integer constant expression that represents the minimum size of a string large enough to hold a file name generated by the tmpnam function.

Macro: int TMP_MAX

The macro TMP_MAX is a lower bound for how many temporary names you can create with tmpnam . You can rely on being able to call tmpnam at least this many times before it might fail saying you have made too many temporary file names.

With the GNU C Library, you can create a very large number of temporary file names. If you actually created the files, you would probably run out of disk space before you ran out of names. Some other systems have a fixed, small limit on the number of temporary files. The limit is never less than 25 .

Function: char * tempnam (const char * dir , const char * prefix )

Preliminary: | MT-Safe env | AS-Unsafe heap | AC-Unsafe mem | See POSIX Safety Concepts.

This function generates a unique temporary file name. If prefix is not a null pointer, up to five characters of this string are used as a prefix for the file name. The return value is a string newly allocated with malloc , so you should release its storage with free when it is no longer needed.

Because the string is dynamically allocated this function is reentrant.

The directory prefix for the temporary file name is determined by testing each of the following in sequence. The directory must exist and be writable.

  • The environment variable TMPDIR , if it is defined. For security reasons this only happens if the program is not SUID or SGID enabled.
  • The dir argument, if it is not a null pointer.
  • The value of the P_tmpdir macro.
  • The directory /tmp .

This function is defined for SVID compatibility.

Warning: Between the time the pathname is constructed and the file is created another process might have created a file with the same name using tempnam , leading to a possible security hole. The implementation generates names which can hardly be predicted, but when opening the file you should use the O_EXCL flag. Using tmpfile or mkstemp is a safe way to avoid this problem.

SVID Macro: char * P_tmpdir

This macro is the name of the default directory for temporary files.

Older Unix systems did not have the functions just described. Instead they used mktemp and mkstemp . Both of these functions work by modifying a file name template string you pass. The last six characters of this string must be ‘ XXXXXX ’. These six ‘ X ’s are replaced with six characters which make the whole string a unique file name. Usually the template string is something like ‘ /tmp/ prefix XXXXXX ’, and each program uses a unique prefix .

NB: Because mktemp and mkstemp modify the template string, you must not pass string constants to them. String constants are normally in read-only storage, so your program would crash when mktemp or mkstemp tried to modify the string. These functions are declared in the header file stdlib.h .

Function: char * mktemp (char * template )

Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.

The mktemp function generates a unique file name by modifying template as described above. If successful, it returns template as modified. If mktemp cannot find a unique file name, it makes template an empty string and returns that. If template does not end with ‘ XXXXXX ’, mktemp returns a null pointer.

Warning: Between the time the pathname is constructed and the file is created another process might have created a file with the same name using mktemp , leading to a possible security hole. The implementation generates names which can hardly be predicted, but when opening the file you should use the O_EXCL flag. Using mkstemp is a safe way to avoid this problem.

Читайте также:  Tablet computers with windows

Function: int mkstemp (char * template )

Preliminary: | MT-Safe | AS-Safe | AC-Safe fd | See POSIX Safety Concepts.

The mkstemp function generates a unique file name just as mktemp does, but it also opens the file for you with open (see Opening and Closing Files). If successful, it modifies template in place and returns a file descriptor for that file open for reading and writing. If mkstemp cannot create a uniquely-named file, it returns -1 . If template does not end with ‘ XXXXXX ’, mkstemp returns -1 and does not modify template .

The file is opened using mode 0600 . If the file is meant to be used by other users this mode must be changed explicitly.

Unlike mktemp , mkstemp is actually guaranteed to create a unique file that cannot possibly clash with any other program trying to create a temporary file. This is because it works by calling open with the O_EXCL flag, which says you want to create a new file and get an error if the file already exists.

Function: char * mkdtemp (char * template )

Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.

The mkdtemp function creates a directory with a unique name. If it succeeds, it overwrites template with the name of the directory, and returns template . As with mktemp and mkstemp , template should be a string ending with ‘ XXXXXX ’.

If mkdtemp cannot create an uniquely named directory, it returns NULL and sets errno appropriately. If template does not end with ‘ XXXXXX ’, mkdtemp returns NULL and does not modify template . errno will be set to EINVAL in this case.

The directory is created using mode 0700 .

The directory created by mkdtemp cannot clash with temporary files or directories created by other users. This is because directory creation always works like open with O_EXCL . See Creating Directories.

Источник

Creating temporary files in bash

Are there objectively better ways to create temporary files in bash scripts?

I normally just name them whatever comes to my mind, such as tempfile-123, since it will be deleted when the script is over. Is there any disadvantage in doing this other than overwriting a possible tempfile-123 in current folder? Or is there any advantage in creating a temporary file in a more careful way?

5 Answers 5

The mktemp(1) man page explains it fairly well:

Traditionally, many shell scripts take the name of the program with the pid as a suffix and use that as a temporary file name. This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win. A safer, though still inferior, approach is to make a temporary directory using the same naming scheme. While this does allow one to guarantee that a temporary file will not be subverted, it still allows a simple denial of service attack. For these reasons it is suggested that mktemp be used instead.

In a script, I invoke mktemp something like

which creates a temporary directory I can work in, and in which I can safely name the actual files something readable and useful.

mktemp is not standard, but it does exist on many platforms. The «X»s will generally get converted into some randomness, and more will probably be more random; however, some systems (busybox ash, for one) limit this randomness more significantly than others

By the way, safe creation of temporary files is important for more than just shell scripting. That’s why python has tempfile, perl has File::Temp, ruby has Tempfile, etc…

Читайте также:  Mac view all windows

It will create a temporary file inside a folder that is designed for storing temporary files, and it will guarantee you a unique name. It outputs the name of that file:

You might want to look at mktemp

The mktemp utility takes the given filename template and overwrites a portion of it to create a unique filename. The template may be any filename with some number of ‘Xs’ appended to it, for example /tmp/tfile.XXXXXXXXXX. The trailing ‘Xs’ are replaced with a combination of the current process number and random letters.

For more details: man mktemp

Is there any advantage in creating a temporary file in a more careful way

The temporary files are usually created in the temporary directory (such as /tmp ) where all other users and processes has read and write access (any other script can create the new files there). Therefore the script should be careful about creating the files such as using with the right permissions (e.g. read only for the owner, see: help umask ) and filename should be be not easily guessed (ideally random). Otherwise if the filenames aren’t unique, it can create conflict with the same script ran multiple times (e.g. race condition) or some attacker could either hijack some sensitive information (e.g. when permissions are too open and filename is easy to guess) or create/replacing the file with their own version of the code (like replacing the commands or SQL queries depending on what is being stored).

You could use the following approach to create the temporary directory:

or temporary file:

However it is still predictable and not considered safe.

As per man mktemp , we can read:

Traditionally, many shell scripts take the name of the program with the pid as a suffix and use that as a temporary file name. This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win.

So to be safe, it is recommended to use mktemp command to create unique temporary file or directory ( -d ).

Источник

mktemp(3) — Linux man page

mktemp — make a unique temporary filename

Synopsis

Description

The mktemp() function generates a unique temporary filename from template. The last six characters of template must be XXXXXX and these are replaced with a string that makes the filename unique. Since it will be modified, template must not be a string constant, but should be declared as a character array.

Return Value

The mktemp() function always returns template. If a unique name was created, the last six bytes of template will have been modified in such a way that the resulting name is unique (i.e., does not exist already) If a unique name could not be created, template is made an empty string.

Errors

The last six characters of template were not XXXXXX.

Conforming To

4.3BSD, POSIX.1-2001. POSIX.1-2008 removes the specification of mktemp().

Notes

The prototype is in for libc4, libc5, glibc1; glibc2 follows the Single UNIX Specification and has the prototype in .

Never use mktemp(). Some implementations follow 4.3BSD and replace XXXXXX by the current process ID and a single letter, so that at most 26 different names can be returned. Since on the one hand the names are easy to guess, and on the other hand there is a race between testing whether the name exists and opening the file, every use of mktemp() is a security risk. The race is avoided by mkstemp(3).

Источник

Оцените статью