I'm trying to control a system service with PHP's shell_exec function :

shell_exec('sudo /usr/sbin/service icecast2 stop');

But the only way I can get it to work is by allowing ALL users root access to the services in /etc/sudoers :

ALL ALL=(root) NOPASSWD: /usr/sbin/service

This is obviously a really bad idea, but it refuses to run if I try to set it to anything else as the service needs root privs eg :

%www-data ALL=(root) NOPASSWD: /usr/sbin/service
%www-data ALL=NOPASSWD: /usr/sbin/service

Also an echo of posix_getpwuid(posix_geteuid())['name']; gives me a different name that is running the process - not www-data. But neither of these work either :

%myphpuser ALL=(root) NOPASSWD: /usr/sbin/service
%myphpuser ALL=NOPASSWD: /usr/sbin/service

I also tried writing a bash script to control the service and call it from shell_exec, but that fails to run to.

Can anybody think of any other solution so I don't leave my services open like this?

For instance, just allowing access to this specific service and function instead?


Made some progress. This works, but is this safe enough?

myphpuser ALL=(ALL:ALL) ALL
myphpuser ALL=NOPASSWD: /usr/sbin/service

Should also mention that the php script that calls this is run by a cron job, it's not public facing in anyway whatsoever.

  • You say “it refuses to run”, “neither of these work either” and “that fails to run [too]”.  Please be more specific about what happened. … … … … … … … … … … … … … … Please do not respond in comments; edit your question to make it clearer and more complete. – G-Man Says 'Reinstate Monica' Feb 28 '19 at 1:48
  • 2
    consider narrowing down the (eventual) sudo rules down to usr/sbin/service icecast2 stop and usr/sbin/service icecast2 start (so that a PHP user can't stop arbitrary services) – Jeff Schaller Feb 28 '19 at 1:52
  • 1
    I think your initial problem was using %foo ; the % means "group", so you were looking for the group "myphpuser" and not the user. – Stephen Harris Feb 28 '19 at 2:04
  • Yes I realised that on my travels after posting this question. Thanks for clarifying though. – spice Feb 28 '19 at 2:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.