Linux – Change file ownership during write operation

linuxpermissions

By default the umask is 0022:

usera@cmp$ touch somefile; ls -l
total 0
-rw-r--r-- 1 usera usera 0 2009-09-22 22:30 somefile

The directory /home/shared/ is meant for shared files and should be owned by root and the shared group. Files created here by usern (any user) are automatically owned by the shared group. There is a cron-job taking care of changing owning user and owning group (of any moved files) once per day:

usera@cmp$ cat /etc/cron.daily/sharedscript

#!/bin/bash

chown -R root:shared /home/shared/
chmod -R 770 /home/shared/

I was writing a really large file to the shared directory. It had me (usera) as owning user and the shared group as group owner. During the write operation the cron job was run, and I still had no problem completing the write process.

You see. I thought this would happen:

  1. I am writing the file. The file permissions and ownership data for the file looks like this: -rw-r--r-- usera shared
  2. The cron job kicks in! The chown line is processed and now the file is owned by the root user and the shared group.
  3. As the owning group only has read access to the file I get a file write error! Boom! End of story.

Why did the operation succeed? A link to some kind of reference documentation to back up the reason would be very welcome (as I could use it to study more details).

Best Answer

Afaik, POSIX 1003.1 requires only fopen to return an [EACCES] error on insufficient privileges. Subsequent operations like fputc might return a [EBADF] bad file descriptor error, but i don't think that is meant to cover permission changes while the file is open.

Years ago, i worked in a company where we had our AIX servers set up so that they used that property to make logfiles more secure. When a service started, root would touch /var/log/service.log, then chown it to serveruser:servergroup, su - start the service (it would open the file in append mode), and then chown the file back to root. Consequently, the service could append to its own logfile, but not delete or overwrite it, so if an attacker managed to compromise the service he couldn't tamper with past log entries.

A similar trick can be used for temporary files: open the file, then remove it. The directory entry is gone and the file is invisible, but since the file handle is still open, the inode is still there. Once you close the file, the link count goes to zero, and the OS reclaims the disk space.

Related Question