在玩C以前玩過一段時間的PHP, 哪個時候需要用PHP 來運行root命令,一直未果,直到有一天搜索到了super這個插件。
隨著玩C的日子多了,發現可以用C語言來包裹 要運行的外部命令。實驗了一下,成功了。不需要任何外部工具就可以實現用PHP 執行root命令。我下面就把方法發布給大家,有需求用php來運行root命令的朋友可以不用發愁了。
平台:Linux
實驗命令iptables,當前的目錄是/var/www/html/http,寫程序的時候用root用戶,大家都知道iptables 非root用戶不能運行。
首先寫個C程序,命名為:ipt.c。
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> int main() { uid_t uid ,euid; char cmd[1024]; uid = getuid() ; euid = geteuid(); printf("my uid :%u\n",getuid()); //這裡顯示的是當前的uid 可以注釋掉. printf("my euid :%u\n",geteuid()); //這裡顯示的是當前的euid if(setreuid(euid, uid)) //交換這兩個id perror("setreuid"); printf("after setreuid uid :%u\n",getuid()); printf("afer sertreuid euid :%u\n",geteuid()); system("/sbin/iptables -L"); //執行iptables -L命令 return 0; }
編譯該文件:
gcc -o ipt -Wall ipt.c
在該路徑下生成ipt,這個可執行文件。如果現在用PHP網頁調用 該ipt的話,即使setreuid了 也是不行的。
接下來要做的是:
chmod u+s ./ipt ls -rwsr-xr-x 1 root root 5382 Jul 2 21:45 ipt
好了,已經設置上了,再寫一個php頁面調用它。
<?php echo '<pre>'; $last_line = system('/var/www/html/http/ipt', $retval); echo ' </pre> <hr />Last line of the output: ' . $last_line . ' <hr />Return value: ' . $retval; ?>
在浏覽器中浏覽。
[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 prot opt source destination [/color] [color=Blue]my uid :48 my euid :0 after setreuid uid :0 afer sertreuid euid :48[/color] --------------------------------------------------------- Last line of the output: afer sertreuid euid :48 --------------------------------------------------------- Return value: 0
該命令執行成功。
眾所周知: apache的uid 為48。調用setreuid後將有效用戶id和實際用戶id互換了。(必須在chmod u+s生效的情況下) 使apache當前的uid為0這樣就能執行root命令了。大家只需要更改 C文件中的system所要執行的命令就可以實現自己的PHP執行root命令了。