Php – Allowing PHP to run specific bash script with root permissions

bashpermissionsPHPsudouser-permissions

I have a php script calling a bash script like this:

<?php
    $result = exec('sudo /bin/bash /var/www/my_bash_script.sh /var/www/vhosts/testsite/htdocs/');
    var_dump($result);
?>

This is the contents of my_bash_script.sh:

#!/bin/bash
svn export --force --no-auth-cache --username myusername --password mypassword http://1.2.3.4/repos/path/to/repo/ $1 2>&1
find $1 -print0 -type d | xargs -0 -n 1 -0 chown -R -v root:root 2>&1
find $1'storage' -print0 -type d | xargs -0 -n 1 chown -R -v apache 2>&1
find $1'shared' -print0 -type d | xargs -0 -n 1 chown -R -v apache 2>&1

The purpose of the script is to do an export from my svn repo and set user permissions correctly.

PHP runs as the apache user.

In order to grant PHP permission to run this script I have added the following line to sudoers:

apache ALL=(ALL) NOPASSWD:ALL

Now obviously this gives PHP too much power, so I want to restrict PHP to just run this specific bash script, but I can't seem to get the syntax right:

apache ALL=(ALL) NOPASSWD:/var/www/my_bash_script.sh

The above just returns an empty string (to the $result PHP variable) – what am I doing wrong?

Thanks!

Edit: – I have already commented out #Defaults requiretty in sudoers.

Best Answer

I may be wrong, but I believe that sudoers also restricts parameters that can be passed to a command/script, not just the command itself.

If you try to run your .sh without the parameter it will likely work e.g.

  sudo /bin/bash /var/www/my_bash_script.sh

So, to tell sudoers to allow that script to be run with any parameters (by apache), you would need to adjust the line like so:

  apache ALL=(ALL) NOPASSWD:/var/www/my_bash_script.sh *

The wildcard would allow apache to run that script with any parameters.

You may also need /bin/bash in that line but I'm not certain

  apache ALL=(ALL) NOPASSWD: /bin/bash /var/www/my_bash_script.sh *

If anyone can confirm or refute my understanding of this it would be much appreciated