Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change user PHP

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.

like image 321
xaav Avatar asked Feb 25 '23 06:02

xaav


2 Answers

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");
like image 79
DarthJDG Avatar answered Feb 26 '23 21:02

DarthJDG


This recent question discusses two options for doing this with PHP:

  • PHP + FastCGI with suexec
  • suPHP
like image 30
AJ. Avatar answered Feb 26 '23 20:02

AJ.