allow user to use sudo cp on a specific directory and only a specific file

Is there a way to allow a user to use sudo cp on a specific directory and only a specific file?

Kind of, but may not offer all the flexibility you want. For instance, to allow user nh2 to copy foo to /home/bar, put in your /etc/sudoers file

nh2  ALL=(ALL) NOPASSWD: /bin/cp foo /home/bar

Drawbacks are (among others):

  1. cp is not as flexible; for instance I have to use exactly the syntax set in the sudoers file. Eventually this means using absolute path for the file to copy.
  2. access right might need fixing. Depending on your requirement, plain cp or using the '-p' option for cp might be enough.

HTH,
/Lew

I would reccomend you check setuid.

You can make a shell script and a small c program to call it with root privileges.

So an example :
You make shell script with USER named test.sh which does cp file1 /etc/
Then you make a C program called execshell (or whatever) which runs that script with system call ( please find examples online for C setuid and system call )

Compile that program.

As root you make chown root:root and chmod 4755 to that C program.
User can now invoke that c program which will execute that shell script with root permisions and copy the file1 to /etc/ as root invoked by USER.

Be carefull tho, setuid needs to be handled with care.
passwd would be a lovely example of setuid in C and exceptions it uses.

Hope that helps.
Regards
Peasant.

Instead of trying to restrict a program that gives him permissions to copy any file, why not use ordinary file permissions to control his access?

The only way that would be possible is if I give write permission on the /etc directory. I don't think thats a good idea. The /etc/resolv.conf keeps getting messed up. I want ordinary users to able to use internet and thats not possible right now with the dns not being set properly. The only way I can think of is by allowing a user to use sudo cp on a specific directory and only a specific file.

1 Like

Is that a real problem? You could create a group for the users that need to edit /etc/resolv.conf, gives write permission to /etc/ and /etc/resolv.conf for that group. As long as the other files in /etc doesn't belong to this group, these users won't be able to mess-up those files (files in /etc belong normally to root:root).

Corona is right: If doable, this way should be prefered over sudo/cp.

Brgds,
/Lew

Not true, directory permissions don't control that. If you chown :group /etc/resolv.conf ; chmod g+rw /etc/resolv.conf then anyone in group will be able to modify it.

Fixing /etc/resolv.conf every time it gets messed up isn't really a solution... It's like stocking extra fire extinguishers instead of fixing a smoking electrical short. If you don't want whatever autoconfig keeps messing up the file to do so, disable it.