I have found many questions that do this through opening up huge holes in permissions or changing user ownership of files. For my current application neither of those is an option. What I am trying to do is use a shell_exec or similar php function to run a .sh script in a totally different folder on my system when a button is clicked on my webpage. The script has to be run from the folder it is in. I am on debian and have installed sudo to allow apache user to run the command by adding these lines:
www-data ALL=(ALL) NOPASSWD:/opt/folder/run.sh start
www-data ALL=(ALL) NOPASSWD:/opt/folder/run.sh stop
www-data ALL=(ALL) NOPASSWD:/opt/folder/run.sh status
$test=shell_exec('cd /opt/folder/ && ./run.sh start&& cd -');
ps -ef | grep
So after a few more attempts I decided to save this for later. I realized that although I was allowing the apache user to run the script as root I hadn't actully told it to. To fix this I made the change
$test=shell_exec('cd /opt/folder/ && sudo ./run.sh start&& cd -');
The added sudo now tells the script to run as root and the entries in visudo allow it to do so without asking for a password. I did change my visodu file to be a bit more slimmed down so now it just has one line.
www-data ALL=(ALL) NOPASSWD:/opt/folder/run.sh
This fits both the security requirements and the user constraints. There are almost no attack vectors open as a chmod 777 or the like would cause and the apache user only has access to the run.sh script with the hard coded perameters it contains.