Vince Rants

Elevating PHP Scripts to Run With Root Privileges

*UPDATE* Don't do this. There is a fundemental flaw with password passing that I initially overlooked. It shows up in the process list. WOMP WOMP!

 

First and foremost: THIS IS EXTREMELY DANGEROUS. Do *NOT* blindly run commands as root, especially from a web application unless you absolutely 100% know what you're doing and lock down any access to this code. More on this in a bit.

First, the code. Two functions are provided here, the first executes a command as the current user. The second executes a command as root.

<?php function user($command) { return rtrim(shell_exec($command), PHP_EOL); } function root($command, $password) { return rtrim(shell_exec( 'echo ' . escapeshellarg($password) . ' | sudo -p "" -S -k ' . $command ), PHP_EOL); } var_dump( user('whoami') ); var_dump( root('whoami', 'password') );

Output:

user@jail:/tmp % php test.php
string(4) "user"
string(4) "root"

Why am I doing this?

I am currently in the process of building a web based administration system for a server or cluster of servers. This web interface needs access to services only available to root.  Some of the administrative tasks this interface will perform is provisioning and manage storage, creating virtual machines, managing jails, and so forth. These tasks are impossible without root privileges. 

Before building these quick little functions, I spend considerable time browsing the web searching for a solution to securely run PHP scripts as the root user. Most people suggested either running the entire PHP process as root or running the Apache server as root. Neither of these solutions is satisfactory to me, because this poses major security risks. I'd rather have PHP run as an isolated user, and only access root privileges when needed, and ONLY when needed.

Securing the root password.

You may have already noticed that this method requires the root password in order to function. What isn't shown here is the session management system in place to store and secure the root password. Much like with the sudo command, the user is prompted to input the root password. This password is used during the session only, stored only in encrypted RAM, never on disk. There is a custom encryption key management system in place to help ensure the root password remains secure.