Call chroot in PHP

2019-08-14 14:36发布

问题:

For security reasons, some applications are isolated in a chroot environment. I need to call this applications through a PHP script. Something like that :

exec('chroot /path/to/chroot command')

I need to be root for using chroot. There is a chroot() in the PHP manual but this function also requires root privileges.

So, how to use chrooted commands in PHP?

回答1:

chroot can only be called by privileged users. Otherwise, normal users could trick setuid applications such as passwd or sudo into accessing files in an unexpected location.

Therefore, if your php application is not running as root, the one thing you can do is set up a setuid wrapper script and call that from php. It should promptly drop privileges after calling chroot, as root can trivially break out of chroots.

Alternatively, you can configure sudo to allow the php user to execute chroot /path/to/chroot command and prepend sudo to the exec call in php.



回答2:

You can use Linux Capabilities. See CAP_SYS_CHROOT capability on man capabilities.

WARNING! By using sudo, after chrooting you are root!



回答3:

The trick here is to use sudo and the sudoers file see the sudo manpage.

Basically what you would do is give your PHP user access to the sudo utility for the chroot command and your code will be like this:

exec('sudo chroot /path/to/chroot command')


标签: php linux chroot