I need to change the user of a PHP script at runtime. I've looked at posix_setuid
, but it looks unsecure and requires root privaledges. What would be preferable is changing the user id of the script with the users password (something like posix_setuid($username, $password)
), and avoiding running the script as root.
I'm open to other methods, and the script doesn't necessarily need to be PHP. However, it is going to be called from apache.
A good anology to the scenario would be how cPanel su's to the currently logged in user on it's file manager.
I need to change the user because I'm creating a file manager for a multi-user setup. Currently, I have the file manager set up so that apache serves my PHP file manager as root. However, this is not reasonable, because in case of a security bug in the code, one user can edit files on the entire server.
I'm looking for a way to SU the script to the logged in user so that in case of a security flaw, the user is only restricted to their own files.
I needed to do this a while ago. I basically created a bash script which accessed resources that only root had access to. Here's what I did:
Use the visudo
command to change your /etc/sudoers
:
## Allow root to run any commands anywhere
root ALL=(ALL) ALL
apache ALL= NOPASSWD: /sbin/myscript.sh
I have added the line which allows the apache
user to run /sbin/myscript.sh
with the sudo command without entering the password.
After that, you can just put the following in your php file to get the output:
$output = shell_exec("sudo /sbin/myscript.sh");
This recent question discusses two options for doing this with PHP:
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