What do you need to run PHP as root? You will need to use visudo and edit the sudoers file. The visudo command is available on all UNIX and Linux systems. It provides a safe of editing the /etc/sudoers file.
The exec() function is an inbuilt function in PHP which is used to execute an external program and returns the last line of the output. It also returns NULL if no command run properly. Syntax: string exec( $command, $output, $return_var )
Don't do it! You will leave yourself wide open to all sorts of malicious hackery.
Have a look at the "sudo" documentation.
You should be able to set up all the commands you need as "sudo"able scripts. It is much better to write specific scripts with limited functions than to expose the underlying priviledged command.
As in:
exec ('sudo getIpTables.ksh')
You can run sudo through phpseclib, a pure PHP SSH implementation:
<?php
include('Net/SSH2.php');
$ssh = new Net_SSH2('www.domain.tld');
$ssh->login('username', 'password');
$ssh->read('[prompt]');
$ssh->write("sudo command\n");
$ssh->read('Password:');
$ssh->write("Password\n");
echo $ssh->read('[prompt]');
?>
I know this is an old question
add the user php runs on to the sudo group if it is not already assigned
use sudo -S, so you can pass the password via echo
$exec = "echo your_passwd | /usr/bin/sudo -S your command";
exec($exec,$out,$rcode);
if you have trouble with the paths - use
"bash -lc 'echo your_passwd | /usr/bin/sudo -S your command'"
so you get a new bash that acts like a login shell and has the paths set
check the man pages of sudo
This is very unsafe and a bad idea. Rethink your design. If you really want to do this use sudo as advised. An alternative solution might be to go ahead and run as root but do so inside a chroot or a vm image (both of which can be broken out of but still).
Or best of all run as sudo inside a chroot!
You can put the required commands in a separate script/executable file (sh, PHP, a real executable, doesn't matter), change its owner to root, and apply "setuid" to it.
This will allow anything and anyone to run this script as root, so you need to make sure that it has it's own security rules for seeing if this is allowed, and is very restricted in what it does.
Unless you use suphp and configure it to run as root you wont be able to run any PHP script on behalf of any other system user besides who is running PHP.
Just an small idea. Add a queue process in some way and run a cron process in the root's crontab.
Please please be really careful about this. Any injection can literally destroy the system.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With