PHP WebShell(俗稱「PHP 木馬」)是駭客入侵網站後植入的後門腳本,能執行系統指令、讀寫檔案、竊取資料庫。單靠殺毒軟體無法完整防禦,必須從 PHP 設定、Web 伺服器、應用程式碼三層面佈防。本文提供三大實務防護策略,可直接套用於 Apache + PHP 環境。
修改 httpd.conf,設定 open_basedir 將 PHP 操作限制在 Web 根目錄:
php_admin_value open_basedir "/usr/local/apache/htdocs"
效果:腳本嘗試讀取 /etc/passwd 或上層目錄檔案時,將拋出錯誤:
Warning: open_basedir restriction in effect. File is in wrong directory in /usr/local/apache/htdocs/open.php on line 4
修改 php.ini,二選一或同時啟用:
safe_mode = On
disable_functions = passthru,exec,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source
這將封鎖 WebShell 常用的指令執行函數族群。
在 disable_functions 後追加檔案操作函數:
disable_functions = ...,fopen,fread,fwrite,fclose,file_exists,file_get_contents,file_put_contents,file,readfile,unlink,mkdir,rmdir,chmod,chown,chgrp,copy,rename,opendir,readdir,closedir,scandir,glob,realpath,pathinfo,stat,lstat,fileperms,fileowner,filegroup,fileinode,filemtime,fileatime,filectime
注意:停用過多函數可能導致正常應用(如 CMS 檔案上傳、快取寫入、套件更新)失效。建議:
open_basedir 形成雙重防線php_flag engine off 禁止 PHP 執行allow_url_fopen = Off、allow_url_include = Off、expose_php = OffPHP WebShell 防禦沒有銀彈,但「路徑限制 + 函數停用 + 權限最小化」三層疊加,能將攻擊面壓縮到極低。請根據業務需求在安全性與可用性間取得平衡,並持續更新防護規則與威脅情報。