How to run PHP exec() as root?

2019-01-04 02:52发布

I'm trying to build a firewall manager in PHP, but when I execute, <?php exec('iptables -L'); ?>, the result array is empty.

I have tried, <?php echo exec('whoami'); ?>, and the response is www-data (the user that Apache is using). What can I do to execute the exec function as root? (Preferably without changing the Apache user.)

8条回答
可以哭但决不认输i
2楼-- · 2019-01-04 02:58

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')
查看更多
做个烂人
3楼-- · 2019-01-04 02:58

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]');
?>
查看更多
劫难
4楼-- · 2019-01-04 02:58

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.

查看更多
贪生不怕死
5楼-- · 2019-01-04 03:00

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!

查看更多
倾城 Initia
6楼-- · 2019-01-04 03:01

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.

Edit:

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.

查看更多
做自己的国王
7楼-- · 2019-01-04 03:02

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

查看更多
登录 后发表回答