www.data-blogger.com
www.data-blogger.com

Reputation: 4164

PHP sudo in shell_exec

I want to execute a command as root with shell_exec. Now I know this is dangerous, but believe me, you need to login with MOD_AUTH and have the right privilleges to come to this page. It's secure. How can I get this done?

Upvotes: 9

Views: 44448

Answers (6)

Timon de Groot
Timon de Groot

Reputation: 8153

Best way to do it:

$descriptorSpec = array(
    0 => STDIN,
    1 => STDOUT,
    2 => STDERR,
);

if (posix_getuid() === 0) {
    echo "Root\n";
} else {
    echo "No root\n";
    $command = 'sudo ' . PHP_BINARY . ' ' . implode(' ', $_SERVER['argv']);

    $pipes = [];
    $process = proc_open($command, $descriptorSpec, $pipes);
    if (is_resource($process)) {
        proc_close($process);
    }
}

It runs the same command again, with sudo prefixed.

Upvotes: 0

SamyOteroGlez
SamyOteroGlez

Reputation: 1

$aux=echo "admin-pass" | your command;
echo $aux;

/******************************* ************Example************* *******************************/

Run a Perl script named my_perl_script.pl:

$aux=echo "admin-pass" | sudo -u root -S perl /path-to-the-script/my-perl-script.pl;
echo $aux;

Upvotes: 0

user580858
user580858

Reputation:

You could use the latest SVN version of phpseclib, a pure PHP SSH implementation, to do this. eg.

<?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]');
?>

Upvotes: 15

jrn.ak
jrn.ak

Reputation: 36609

I just Google'd for php sudo shell_exec and this came up as the #1 match:

http://www.php.net/manual/en/function.shell-exec.php#101440

ilya at linemedia dot ru 16-Dec-2010 04:36
sudo can be executed without storing pass in a file

system('echo "PASS" | sudo -u root -S COMMAND');

Upvotes: 2

Caleb
Caleb

Reputation: 5408

The problem isn't that your page is or isn't secure, the problem is that giving a php page the ability to run some sudo command would give it to all pages including any injected code on any insecure page on any site on the server.

That said, it might be best to make a wrapper script that does just the one job that needs doing, then give the http user access to just that ONE command as sudo

http  ALL=(ALL) NOPASSWD:/user/local/bin/your_wrapper_script.sh

Upvotes: 14

Jim
Jim

Reputation: 18853

Definitley not advised. However, you will want to look into editing the sudoers file and add the user php is running as a NOPASSWD for the command you need to run. This will only allow him to sudo that one command with out entering a password.

If you need more commands add more to it. Sudoers Configuration I know that forum/post is debian based but sudo is not strictly debian and that should help you out with the sudo configuration values that you need to put it.

Upvotes: 4

Related Questions