The possibility of this attack is not something that is inevitable in the use of temp files. It stems from an insecure implementation of temp files.
For instance, on a Unix system, a hole can be opened if the temporary file directory has incorrect permissions. The /tmp
directory is shared by users, and so everyone has write permission to the directory itself (to be able to create files). But a special "sticky bit" permission is applied which prevents users from being able to delete files which they do not own. If that permission bit is missing, then it is possible for a malicious process to create a race condition attack: it notices that a temporary file has just been created, and, before the owning process can use it, it deletes the file and replaces it with its own. (Applications could check the ownership and permissions of the temp file they have just opened, but probably few, if any, bother, because programs are written to trust that the temporary directory is correctly configured.)
If a temporary file is created with incorrect permissions, then it can be accessed and tampered with. Programs that use temporary files must create them with the appropriate permissions. This means that certain highly platform-independent file manipulation functions cannot be used. For instance if we use the C function fopen
to create a temporary file, we have a security hole, because fopen
does not have any parameters to control what permissions the file will have. On a Unix-like system, it will create a file with liberal permissions (minus only those permissions removed by umask
). Platform-specific library functions should be used for creating and opening temporary files.
A program, when it creates a temporary file, always checks whether that file does not exist already. However, this check has to be atomic, otherwise there is a race condition between checking that the file does not exist and opening/creating the file. That race condition is not fixed by correct permissions on the temporary directory. It is fixed by using an atomic operation for creating the file. On Unix, the O_EXCL
flag is used in addition to O_CREAT
to ask the operating system to fail the open
call if the file already exists, otherwise to create it. A potential pitall here is hosting the temporary file directory on some network filesystem which does not honor the atomic semantics of O_EXCL
.
Of course, temporary files are not protected against attack from the same security context. (At least, not without the implementation of fine-grained security policies in the OS.) If a malicious program runs as user joe
aleady, then that program can attack temp files created by programs that are running as user joe
. To prevent that sort of thing, you need a security scheme which is finer grained than simple account-based security domains. For instance a security system with rules such as: "only executable /bin/foo
is allowed to access any filesystem object whose path matches the pattern /tmp/foo*
".