Linux Shell Files Security CP – Is cp –no-clobber Vulnerable to Race Condition?

cpfileslinuxSecurityshell

The man page for cp(1) says

--no-clobber do not overwrite an existing file

However, wouldn't the following scenario be possible?

  1. cp checks the file existence, let's assume the file doesn't exist (yet)
  2. Some other process writes to the same path, so now there is data written to the previously not existing file
  3. Since cp isn't aware of the now existing file, it overwrites the data

Is cp --no-clobber vulnerable to this race condition? And if not, how does cp avoid the situation above?

Best Answer

cp isn’t vulnerable to this race condition. When --no-clobber is set, it checks whether the destination already exists; if it determines it doesn’t, and it should therefore proceed with the copy, it remembers that it’s supposed to copy to a new file. When the time comes to open the destination file, it opens it with flags which enforce its creation, O_CREAT and O_EXCL; the operating system then checks that the file doesn’t exist while opening it, and fails (EEXIST) if it does.

Related Question