How to let the user execute a command containing quotes in sudoers?

I have this command

chroot /chroots/box /bin/bash -c 'cd /repos/system && git pull'

I tried to write in /etc/sudoers

user ALL = (root) NOPASSWD: chroot /chroots/box /bin/bash -c 'cd /repos/system && git pull'

but that didn’t work. In logs I’ve seen

sudo:      user : command not allowed ; TTY=pts/7 ; PWD=/home/user ; USER=root ; COMMAND=chroot /chroots/box /bin/bash -c cd /repos/system && git pull

I’ve also tried to escape quotes in sudo call, like \', and they appeared in log file with the same error.

This repo affects the root filesystem of the chroot, so I can’t call git pull from the outside.


Solution 1:

The simple solution is to put your command in a script and then give your users access to the script via sudo.

user ALL = (root) NOPASSWD: /path/to/yourscript

Then

#/bin/bash
chroot /chroots/box /bin/bash -c 'cd /repos/system && git pull'

Ensure that your users do not have write access to yourscript.

Solution 2:

edit: Warning, it appears that sudo does not safely handle spaces in the command, so it is not safe to use sudo in this way. https://unix.stackexchange.com/a/279142/39281

Instead of using quotes in the sudoers file, you can escape spaces using backslash:

user ALL = (root) NOPASSWD: chroot /chroots/box /bin/bash -c cd\ /repos/system\ &&\ git\ pull

You can still use it as follows, because the user's shell handles the quoted argument anyway:

chroot /chroots/box /bin/bash -c 'cd /repos/system && git pull'

Personally I like the other answer, to put it in a script, but this answers the actual question.