9

If you try to append to a file with no write permissions (say, the /etc/sudoers file which is is owned by root and has 0440 permissions), if you're the actual root user, this works. However, if you're another user using sudo, you get a permission denied error.

Why is this? It not because of the ownership of the file - it doesn't work with files owned by the normal user either. The real root user seems to have more permissions than are granted with sudo. What's the rationale for this? Is there a way to grant this permission to users using sudo?

fields
  • 690
  • 1
  • 10
  • 21
  • This question could use a more clear title.... – mattdm Dec 17 '10 at 18:12
  • Does this answer your question? [\`sudo echo "bla" >> /etc/sysctl.conf\` permission denied](https://serverfault.com/questions/540492/sudo-echo-bla-etc-sysctl-conf-permission-denied) –  Jan 25 '20 at 18:22

2 Answers2

15

Sounds like you're doing something like:

sudo echo "blah blah blah de blah" >> /etc/protected_file

This doesn't work because sudo applies to the echo command, which happily runs as root, but the redirect is part of your current shell, which isn't running as root.

Common solutions are:

sudo bash -c 'echo "blah blah blah de blah" >> /etc/protected_file'

and

echo "blah blah blah de blah" | sudo tee -a /etc/protected_file
mattdm
  • 6,600
  • 1
  • 26
  • 48
3

Note: You should be using "visudo" to edit the sudoers file, because it checks the file for syntax errors before letting you commit them, to prevent you from locking yourself out.

Sean Reifschneider
  • 10,720
  • 3
  • 25
  • 28
  • I understand that. However, as far as I can tell, there's no way to use visudo non-interactively, and this needs to be done in a script that programmatically adds sudo access for a new user. – fields Dec 16 '10 at 16:35
  • Fair enough, I was just reminded of another question recently where someone locked themselves out by not using visudo. – Sean Reifschneider Dec 16 '10 at 17:40
  • 5
    @fields: the best solution for that is to have a group (`wheel`, traditionally, for full root access) that is granted sudo access. Then, you don't need to edit the sudoers file. You just use `gpasswd -a` (or other appropriate command for your distribution) to add the user to the group. – mattdm Dec 16 '10 at 17:44