Hello,

I've discovered an unexpected behaviour when extracting a tar archive file overwriting existing files with the setuid flag, which I believe is a bug in GNU tar.

It's reasonable to expect that extracting the same tar file the second time to the same location overwriting existing files should not result in any change. However, that's not the case with GNU tar 1.35 running as root when a file in the tar archive has the setuid flag set. In such case, each time the tar archive is extracted, the setuid flag on the corresponding file on the destination filesystem will get flipped.

To reproduce it, run the shell script below as root:

   #!/bin/sh
   set -e

   # check the current user, because
   # tar --preserve-permissions only works for the root user
   myuid="$(id -u)"
   if [ "${myuid}" -ne 0 ]; then
        echo "ERROR: this script can only run as root" >&2
        exit 1
   fi

   # show the tar version
   tar --version

   # create the test files
   filename="foo"
   workdir="$(mktemp -d)"
   testfile="${workdir}/${filename}"
   tarfile="${workdir}/${filename}.tar"
   echo "hello world" >"${testfile}"
   chmod 4755 "${testfile}"
   tar -cf "${tarfile}" -C "${workdir}" "${filename}"

   # show the current status before extracting the tar file
   echo "The original file:"
   ls -l "${testfile}"

   echo "The tar file:"
   tar -tvf "${tarfile}"

   # extract the same tar file multiple times to see the effects
   for i in 1 2 3 4; do
        tar -xf "${tarfile}" -C "${workdir}" --overwrite
        echo "The test file after extracted the tar file ${i} times:"
        ls -l "${testfile}"
   done

   # clean up the test files
   rm -rf "${workdir}"

I've tested it on Ubuntu 24.04, Fedora 42 and Archlinux, the script outputs are the same as below:

   tar (GNU tar) 1.35
   Copyright (C) 2023 Free Software Foundation, Inc.
   License GPLv3+: GNU GPL version 3 or later
   <https://gnu.org/licenses/gpl.html>.
   This is free software: you are free to change and redistribute it.
   There is NO WARRANTY, to the extent permitted by law.

   Written by John Gilmore and Jay Fenlason.
   The original file:
   -rwsr-xr-x 1 root root 12 Apr 17 09:02 /tmp/tmp.mczXEplehs/foo
   The tar file:
   -rwsr-xr-x root/root        12 2025-04-17 09:02 foo
   The test file after extracted the tar file 1 times:
   -rwxr-xr-x 1 root root 12 Apr 17 09:02 /tmp/tmp.mczXEplehs/foo
   The test file after extracted the tar file 2 times:
   -rwsr-xr-x 1 root root 12 Apr 17 09:02 /tmp/tmp.mczXEplehs/foo
   The test file after extracted the tar file 3 times:
   -rwxr-xr-x 1 root root 12 Apr 17 09:02 /tmp/tmp.mczXEplehs/foo
   The test file after extracted the tar file 4 times:
   -rwsr-xr-x 1 root root 12 Apr 17 09:02 /tmp/tmp.mczXEplehs/foo

Note the file permissions flipped between "-rwxr-xr-x" and "-rwsr-xr-x" after each run of "tar -x". This should never have happened.

If you need any further information, please don't hesitate to contact me.

Bowen

Reply via email to