How to run linux commands as root from a PHP app

Adetunji 'TeeJay' Opayele
HostCabal
Published in
2 min readAug 5, 2018
“A little penguin standing on a path in Península Valdés” by Giorgio Parravicini on Unsplash

I often find myself in situations where i need to run system commands right from my php project. Some activities like restarting a linux service for example require you to be root (superuser) to run.

However you cannot ‘sudo’ from your php application and it is not advisable to give your web server user root privilege, so we have to get a lil creative here.

disclaimer: make sure you really know what you are doing before you run a command as root ooo…

Okay! Let’s jump right into it.

The general idea is to write a tiny C program to run your command as root. As an example we’ll create a wrapper to restart the mysqld service from php as root.

  1. Create a c program to run the system command as root no matter what user executes it.
# nano restart_mysql.c
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main (int argc, char *argv[])
{
setuid (0);

system ("/sbin/service mysqld restart");

return 0;
}

2. Compile the c program and set the binary ownership to root with root permission.

# gcc restart_mysql.c -o restart_mysql
# chown root restart_mysql
# chmod u=rwx,go=xr,+s restart_mysql

Voila! now restart_mysql binary will always run as root and execute the commands coded into it. Last thing we have to do is to execute the restart_mysql binary from our php code like so

functions restartMysql()
{
exec('/path/to/restart_mysql');
}

All done!

You can create multiple c binaries to run different root command and exec() them in your php as required.

If you find that you have to update the command to executed often or you need to execute a series of commands, you can create a shell script that contains the commands to be executed as root.

# nano my_shell.sh
#!/bin/sh
/sbin/service ftpd restart
echo 'restart done' > log.txt

then set the file ownership to root and make it only writable by root

# chown root my_shell.sh
# chmod u=rwx,go=xr my_shell.sh

Now update your c program to run the shell script as root.

# nano root_shell.c
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main (int argc, char *argv[])
{
setuid (0);

/* Only use an absolute path to the script,
* a malicious user might take advantage of this
* */

system ("/bin/sh /path/to/my_shell.sh");

return 0;
}

Compile the c program and set the binary ownership to root with root permission.

# gcc root_shell.c -o root_shell
# chown root root_shell
# chmod u=rwx,go=xr,+s root_shell

All done! root_shell will run as root and execute the commands found in the my_shell.sh, Now you can change the commands in the shell script without having to recompile the binary.

Hope you find this useful.

Please share your thoughts or challenges in the comment. I’d love to help in any way i can.

Cheers!

--

--