From the chown(2) man page:
Only a privileged process (Linux: one with the
CAP_CHOWNcapability) may change the owner of a file. The owner of a file may change the group of the file to any group of which that owner is a member. A privileged process (Linux: withCAP_CHOWN) may change the group arbitrarily.
Your process is neither privileged, nor changing the group of a file it owns to a group the owner is in.
Therefore you will need to gain suitable privilege. The two easiest ways to do so are
- Write a minimal binary program (probably in C) to set the ownership of that file (I'm assuming that the file's pathname can be hard-coded, to prevent abuse) and make it set-user-id to root, or even better, add
CAP_CHOWNcapability withsudo setcap cap_chown+ep <program_name>, which won't make the program run asrootwith all of it's consequences.Write a minimal binary program (probably in C) to set the ownership of that file (I'm assuming that the file's pathname can be hard-coded, to prevent abuse) and make it set-user-id to root, or even better, add
CAP_CHOWNcapability withsudo setcap cap_chown+ep <program_name>, which won't make the program run asrootwith all of its consequences. - Write a suitable
/etc/sudoersentry to permit that particular command to be executed usingsudowithout a password.Write a suitable
/etc/sudoersentry to permit that particular command to be executed usingsudowithout a password: write a line such asbar ALL = (root) NOPASSWD: /bin/chown foo:server '/full/path/to/file'
to a file in /etc/sudoers.d (and check that /etc/sudoers has a corresponding #includedir directive - most Linux distributions do). Make sure the command called by your script matches exactly!