How can I allow a user to edit a specific system file normally restricted to root?
Solution 1:
Instead of usingsudo
, just set an ACL on the file:
$ ls -l /var/tmp/foo
-rw-rw---- 1 root root 4 Jul 31 15:26 /var/tmp/foo
$ sudo setfacl -m u:white:rw /var/tmp/foo
$ whoami
white
$ cat /var/tmp/foo
bar
Now the file is owned by 'root' but the user 'white' can read and write to it. The user 'white' can now use his/her favorite editor to edit the file.
Solution 2:
Prepare a script that do the editing you want, for example a script that write the correct file with the static IP (what to put in this script is out of the scope of this Q&A). Let's call this script /root/set_static_ip
. (1)
Edit /etc/sudoers
(2) (with visudo
is better, it checks for sanity, it is very difficult to recover a system with an invalid sudoers file, even impossible from remote (3)), and add
user_name_to_authorize ALL=NOPASSWD: /root/set_static_ip
Now that user is able to use sudo /root/set_static_ip
without any password asked, and the script will run with all privileges; no other command will be allowed.
If you want the user to just replace a file with whatever they want, the script could simply be (call it /root/unsafe-overwrite-interface
)
#! /bin/bash -e
#
cp /tmp/temp-iface.txt /etc/network/interfaces
exit 0
... and you tell the user to edit /tmp/temp-iface.txt
and then run sudo /root/unsafe-overwrite-interface
--- enabling it in sudoers as specified above. Or you can add the user to an ACL list and give them write permission on the specific file.
But notice that if you do not check the file contents for safety, havoc will happen, either intentional or unintentional.
Footnotes:
(1) this script must be as safe as possible. Check inputs and so on. It will be executed with full permissions.
(2) in modern sudo installation, you can add a file to /etc/sudoers.d/
directory which is better --- will survive updates.
(3) I normally keep a terminal with a root session open (sudo -i
) when I modify the sudoers mechanism, and a backup handy.