Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Wiki Markup
This solution is also non-compliant because it violates \[[FIO32-C|FIO32-C. Temporary file names must be unique when the file is created]\] and \[[FI042-C|FI042-C. Temporary files must be removed before the program exits]\]. 

Compliant Solution: mkstemp() (POSIX)

A reasonably secure solution for generating random file names is to use the mkstemp() function. The mkstemp() function is available on systems that support the Open Group Base Specifications Issue 4, Version 2 or later.

A call to mkstemp() replaces the six Xs in the template string with six randomly-selected characters:

Code Block

char template[] = "/tmp/fileXXXXXX";
if ((fd = mkstemp(template)) == -1) {
   err(1, "random file");
}

The mkstemp() algorithm for selecting file names has proven to be immune to attacks.

Code Block
bgColor#ccccff

char sfn[15] = "/tmp/ed.XXXXXX";
FILE *sfp;
int fd = -1;

if ((fd = mkstemp(sfn)) == -1 || (sfp = fdopen(fd, "w+")) == NULL) {
  if (fd != -1) {
    unlink(sfn);
    close(fd);
  }
  fprintf(stderr, "%s: %s\n", sfn, strerror(errno));
  return (NULL);
}

Implementation Details

In many older implementations, the name is a function of process ID and time--so it is possible for the attacker to guess it and create a decoy in advance. FreeBSD has recently changed the mk*temp() family to get rid of the PID component of the filename and replace the entire thing with base-62 encoded randomness. This raises the number of possible temporary files for the "default" usage of 6 X's significantly, meaning that even mktemp() with 6 X's is reasonably (probabilistically) secure against guessing, except under very frequent usage Kennaway 00.

Compliant Solution: tmpfile_s() (ISO/IEC TR 24731-1 )

The ISO/IEC TR 24731-1 function tmpfile_s() creates a temporary binary file that is different from any other existing file
that is automatically removed when it is closed or at program termination. If the program terminates abnormally, whether an open temporary file is removed is implementation-defined.

The file is opened for update with "wb+" mode which means "truncate to zero length or create binary file for update." To the extent that the underlying system supports the concepts, the file is opened with exclusive (non-shared) access and has a file permission that prevents other users on the system from accessing the file.

The tmpfile_s() function is available on systems that support ISO/IEC TR 24731-1 (e.g., Microsoft Visual Studio 2005).

Code Block
bgColor#ccccff

...
if (tmpfile_s(&file_ptr)) {
  /* Handle Error */
}
...

Wiki Markup
The {{tmpfile_s()}} function may not be compliant with \[[FI042-C|FI042-C. Temporary files must be removed before the program exits]\] for implementations where the temporary file is not removed if the program terminates abnormally.

Include Page
c:FIO39 CS mkstemp
c:FIO39 CS mkstemp

...