Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing root commands from PHP...Is there a safe way?

Tags:

command

php

root

I was thinking about to make a little web-based Linux control panel (just for fun).

First potential problem that came to my mind is that i would need to give Apache's user root-level permissions to run those commands, which would compromise the security of the whole system.

Installing a dedicated web server for the system is not really an option.

Maybe I could run a 2nd Apache instance (keeping the 1st one for regular users) but not even sure if possible.

So, what you guys think? What are my best options here?

Thanks in advance for any input.

EDIT: Ok guys thanks for all the suggestions, i'll keep them in mind.

like image 617
Crasher Avatar asked May 05 '12 21:05

Crasher


2 Answers

Write specific scripts that can be run as root and use the setuid bit to do it, so that Apache can run just those scripts as root. IE

#! /usr/bin/php (or wherever your php binary is)
<?php
   // Some PHP code that takes in very limited user input,
   // validates it carefully, and does a sequence of actions
   // that you need to run as root.

   // This could easily be a shell script (or whatever else you want)
   // instead of PHP. That might be preferable in many situations.
?>

Then make sure that that script is owned by root and group'd by your user that Apache runs as:

chown root:www-data myscript.php

Then make it run as owner:

chmod u+s myscript.php

And make sure that Apache can execute it:

chmod g+x myscript.php
like image 186
Paul Avatar answered Sep 25 '22 01:09

Paul


Executing root commands via webserver seems like an insane idea to me, but anyway.

You could use sudo which would make sure that you won't run any unwanted commands.

Little example taken from here, sudo config:

peter, %operator ALL= /sbin/, /usr/sbin, /usr/local/apps/check.pl

And in php:

exec( 'sudo /usr/local/apps/check.pl ...');

Be sure to escape all arguments correctly and so on.

Or you could rather build db table like this:

commands (
    action,
    serialized_parameters.
    result,
    return_code
)

Use php to insert commands to this table and the another script which will be run in cron by different user. You won't have real time results (but you can have them 30 seconds old) but apache user won't be able to use any command directly (of course you can limit actions easily when reading records).

like image 33
Vyktor Avatar answered Sep 24 '22 01:09

Vyktor