0

How can I allow these commands in PHP:

$output = exec('sudo nginx -t 2>&1');
$output2 = exec('sudo /usr/sbin/service nginx reload 2>&1');

I've looked into sudo visudo in the terminal , but it seems like that will give access to all sudo commands, when I only need the two above.

I guess the reload one isn't so important, as I can just run a cron job to do that.

I am using NGINX, with Ubuntu 20 + PHP 7

  • There's a very [simple polkit-based solution](https://serverfault.com/a/841150/126632) that would avoid sudo but it's not available on Ubuntu (because of a questionable design decision they inherited from Debian). Consider using a Linux distribution not based on Debian. – Michael Hampton Feb 15 '21 at 22:58
  • So you're running PHP as root? That sounds even worse than a Debian based OS. – Ginnungagap Feb 15 '21 at 23:35

1 Answers1

0

You can put the following lines in /etc/sudoers.d/nginx:

www-data ALL = (root) NOPASSWD: /usr/sbin/nginx -t
www-data ALL = (root) NOPASSWD: /usr/sbin/service nginx reload

This disables password prompt when running sudo /usr/sbin/service nginx reload or the other command when logged in as www-data.

This assumes that your PHP is running under www-data user.

Tero Kilkanen
  • 34,499
  • 3
  • 38
  • 58
  • Appreciate it, this works! Also, do you think it's much of an issue to allow these commands from a security point? It shouldn't matter that much right, since it's just an nginx reload – Tom Tucker Feb 16 '21 at 15:39
  • This in itself isn't a security issue. However, if you allow modifying nginx configuration via PHP scripts, then there can be security issues. – Tero Kilkanen Feb 16 '21 at 16:00