Allow user to run a command with arguments (which contains spaces)

  1. Write a script (writeable only by root)
  2. In that script, execute the grep you need
  3. In the sudoers config, allow only access to that script
  4. Configure whatever tool or advise whichever user to just run the script via sudo

Much easier to debug, easier to lock down specific access to a specific file, and much harder to exploit.


Apparently, sudo flattens the command into a string before comparing it to a specification in the sudoers file. So, in your case, you don't need to use quotes or any other form of escaping:

user ALL=(root) NOPASSWD: /bin/grep string I want ( /var/log/thefilename.log

Edit: As @user23013 points out in the comments, this can be exploited to grep for "string I want" in any file (and, by extension, also for "string I" and "string".) Please make a careful consideration before using sudo's argument checking!


Also note that the following invocations are equivalent, i.e. you won't be able to restrict users to one specific representation:

sudo grep "string I want (" /var/log/thefilename.log
sudo grep 'string I want (' /var/log/thefilename.log
sudo grep string\ I\ want\ \( /var/log/thefilename.log

This is due to the fact that quotes and escaping is handled by the shell and never reach sudo.


Since you only need root for the file access, consider using cat, tee or something similar and piping that to grep or whatever program you need to run. E.g. sudo cat /file/path | grep … This way you restrict root to where you absolutely need it.

Tags:

Sudo