Linux File Capabilities are lost when I modify the file. Is this expected behavior

capabilitieslinuxxattr

When I modify a file, the file capabilities I had set earlier are lost. Is this the expected behavior?

I first set a file capability:

$ setcap CAP_NET_RAW+ep ./test.txt
$ getcap ./test.txt
./test.txt = cap_net_raw+ep

As expected I found the file capability is set.

Then I modify the file.

$ echo hello >> ./test.txt

Now when I check the file capabilities, no capabilities are found.

$ getcap ./test.txt

Best Answer

Yes it is expected behaviour. I don't have a document that says it but you can see in this patch from 2007

When a file with posix capabilities is overwritten, the file capabilities, like a setuid bit, should be removed.

This patch introduces security_inode_killpriv(). This is currently only defined for capability, and is called when an inode is changed to inform the security module that it may want to clear out any privilege attached to that inode. The capability module checks whether any file capabilities are defined for the inode, and, if so, clears them.

security_inode_killpriv is still in the kernel today, being called from notify_change when an inode is changed in "response to write or truncate": see dentry_needs_remove_privs

 /* Return mask of changes for notify_change() that need to be done as a
  * response to write or truncate... */
 int dentry_needs_remove_privs(struct dentry *dentry)
Related Question