Home >Backend Development >PHP Tutorial >Execute root command in PHP_PHP tutorial
I studied PHP for a while before learning C. When did I need to use PHP to run the root command, I failed until one day I searched for the super plug-in.
As I learned C more and more, I discovered that the external commands to be run can be wrapped in C language. I experimented and it worked.
You can use PHP to execute root commands without any external tools.
Platform: Linux. Experimental command iptables The current directory is /var/www/html/http
When writing programs, use root user
Everyone knows that iptables cannot be run by non-root users.
First write a C program
Named: ipt.c
[CODE]
#include
#include
#include
#include
int main()
{
uid_t uid,euid;
uid = getuid();
euid = geteuid();
printf("my uid:%u
",getuid()); //The current uid shown here can be commented out.
printf("my euid:%u
",geteuid()); //What is displayed here is the current euid
If(setreuid(euid, uid)) //Exchange these two ids
perror("setreuid");
Printf("after setreuid uid:%u
",getuid());
Printf("afer sertreuid euid :%u
",geteuid());
system("/sbin/iptables -L"); //Execute iptables -L command
Return 0;
}
[/CODE]
Compile the file gcc -o ipt -Wall ipt.c
Generate the ipt executable file in this path.
If you now use a PHP web page to call the ipt, it will not work even if you setreuid.
The next thing to do is chmod u+s ./ipt
ls
-rwsr-xr-x 1 root root 5382 Jul 2 21:45 ipt
The s bit has been set.
Write another php page to call it.
[CODE]
echo ; <br>
<br>
$last_line = system(/var/www/html/http/ipt, $retval); <br>
<br>
echo <br>
Last line of the output: . $last_line .
Return value: . $retval;
?>
[/CODE]
View in browser.
[color=Red]Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain FORWARD (policy DROP)
target prot opt source destination
ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED
Chain OUTPUT (policy ACCEPT)
Target prop Opt Source Destination [/color]
[color=Blue]my uid :48
my euid :0
after setreuid uid :0
afer serrtreuid euid :48[/color]
-------------------------------------------------- -------------------------------
Last line of the output: afer sertreuid euid :48
-------------------------------------------------- -------------------------------
Return value: 0
The command was executed successfully..
As we all know: the uid of apache is 48. After calling setreuid, the effective user id and the actual user id are exchanged. (Must be when chmod u+s is in effect) Make the current uid of apache 0 so that you can execute the root command.