Gzip change file ownership

gzippermissionsunix

Here is a case I don’t understand.

I have a group bar, and this group has two users; foo and bar.

I have a test.txt file, foo is the owner and bar user only can read it.

However, if bar user run the gzip command to this file, the ownership changes from foo to bar.

Therefore, foo cannot touch this file any more.

Is this a security hole?

Logged in as bar

$ whoami
bar
$ cd /home/foo/test
$ ls -al
total 8
drwxrwxr-x 2 foo bar  4096 Jan  6 15:48 . 
drwxrwxr-- 5 foo bar  4096 Jan  6 15:48 ..
-rwxr-xr-x 1 foo foo    0 Jan  6 15:48 test.txt
$ gzip test.txt    
$ ls -al
total 12
drwxrwxr-x 2 foo bar 4096 Jan  6 15:50 . 
drwxrwxr-- 5 foo bar 4096 Jan  6 15:48 ..
-rwxr-xr-x 1 bar  bar   29 Jan  6 15:48 test.txt.gz
$ uname -a
Linux 2.6.18-xenU-ec2-v1.2 #2 SMP x86_64 x86_64 x86_64 GNU/Linux

Logged in as a foo:

$ whoami
foo
$ touch test.txt.gz 
touch: cannot touch `test.txt.gz': Permission denied

Best Answer

Its not a security hole. Gzip creates a new file and removes the old one. This is governed by the directory permissions and not the permissions on the file. If you remove write permission from the directory your test.txt will be safe from user bar.

The full process with respect to security looks like this:

  1. Gzip uses read permission on original file to obtain a read-only file handle on original file.
  2. Use write permission on directory to create new, empty file.
  3. Read data from original file and write compressed data to new file
  4. Delete old file using write permission on directory.
Related Question