Perrmission to run specific command by sudo as www-data users without password

Solution 1:

Careful with your solution: you can start, stop or restart any service that way!

Better create a shell script that runs this command:

echo "#!/bin/sh' > /usr/bin/amixer_restart
echo "sudo -u user service amixer restart' >> /usr/bin/amixer_restart

Grant adequate permissions (550 mean root and group www-data can read and execute, nobody can write)

sudo chown root:www-data /usr/bin/amixer_restart
sudo chmod 550 /usr/bin/amixer_restart

And allow apache to sudo on this script:

www-data        ALL=(ALL) NOPASSWD: /usr/bin/amixer_restart

Solution 2:

This is what I ended up doing:

  1. Install apache2 by running sudo apt-get install apache2
  2. Make sure apache is allowed to run cgi scripts by running sudo a2enmod cgi
  3. Restart apache sudo service apache2 restart
  4. Verify that I can run bash scripts by creating the following script at /usr/lib/cgi-bin/test.sh

    #!/bin/bash
    
    # get today's date
    OUTPUT="$(date)"
    USR=$(whoami)
    
    # headers
    echo "Content-type: text/plain"
    echo ""
    
    # body
    echo "Today is $OUTPUT"
    echo "Current user is $USR"
    
  5. make the script executable chmod +x /usr/lib/cgi-bin/test.sh

  6. Verify I am able to execute the script curl localhost/cgi-bin/test.sh I get back the following response:

     Today is Wed Sep  6 12:19:34 PDT 2017 
     Current user is www-data
    
  7. Because the user is www-data I then add that user as a sudoer. I then modify the file /etc/sudoers by adding this line at the end:

    www-data ALL=(ALL) NOPASSWD: ALL

  8. Now that user is supposed to have root privileges. Then I modify my test.sh script as:

    #!/bin/bash
    
    # get today's date
    OUTPUT="$(date)"
    USR=$(sudo whoami)
    
  9. Then you should see the following response when executing a get request agains localhost/cgi-bin/test.sh:

    Today is Wed Sep  6 12:28:38 PDT 2017
    Current user is root