This is a bit of a kludge, but in some cases it is actually very helpful. For instance, if your employer has tasked you with securing one of those monster applications that have been around for years now. These beasts more often than not use temporary files in many places, and don't care much whether they do it safely or not. Sometimes, the code is so convoluted that cleaning it up and making it use mkstemp would amount to rewriting major parts of it. In this case, it can be helpful to make the application use a private temporary directory.
Doing this is pretty straightforward. In contrast to creating a regular
file, creating a directory does not follow symlinks. So if you invoke
the mkdir system call to create /tmp/foo, but
/tmp/foo is a symlink, the system call will fail.
strcpy(dirname, "/tmp/fooXXXXXX");
if (mktemp(dirname) == NULL
|| mkdir(dirname, 0700) < 0)
fatal("Unable to create temporary directory: %m");
putenv("TMPDIR", dirname);
Note that the directory mode of 700 is actually crucial, because
it makes sure only the user who created this directory has write access.
If we created the directory using a mode of 0775, we would give
all members of the directory's group write access as well, allowing them
to play symlink tricks on us!
Once you have created that directory, your application can safely create and delete files within that directory, because it will not be accessible to untrusted users. All you need to do now is go over the code and make sure that whenever a temporary file is located, it is placed in this ``safe'' directory. Beware, some library functions such as tempnam evaulate the TMPDIR environment variable to find out where temporary files should go. As a matter of caution, you should therefore set this variable (shown above).
BSD and recent versions of the GNU libc used by Linux support a mkdtemp call for creating a temporary directory much like mkstemp does for regular files.