Tuesday, August 30, 2005

Race conditions accessing files

After a brief thread with smb4k upstream, I noticed that it is not evident for many developers that accessing files (temporary or not) could expose to race conditions exploits in some situations, if the program runs in privileged mode or not. That's quite worrying, because Debian GNU/Linux has tons of little tools which are not so often inspected for security auditing. So folks, be so nice to read the following recommendations and consider that accessing files could be potentially a risky business:
  • do not use fixed or easily guessable pathnames for files in /tmp or any other world -accessible directory.
  • do not use nothing different from mkstemp() or tmpfile() to open temporary files and consider that mkstemp() does not work properly on NFS (due to O_EXCL use)
  • double check if you are using correct ownership and permission
  • unlink temporary files just after opening and use the open handle after
  • check if you are accessing a symlink or a pipe and do not accept anything different from a plain file
  • do not accept any path which has a symlink in a subpath
  • do not overwrite an existent file and if your temporary files need explicit deletion do not forget to do it on exit
  • checks and opening must be done atomically
  • tempnam() and its sister calls are evil
  • creating a temporary directory and files there is better for atomicity against race conditions
  • doing IPC without a named file is surely safer