PHP文件包含漏洞防护方案咨询
Hey there, let's walk through the concrete solutions you need to mitigate that PHP file inclusion vulnerability and block external requests effectively:
针对PHP文件包含/代码注入漏洞的最佳防护方案
- 强制使用白名单机制:Never rely on user-controlled variables directly for
include/requireparameters. If dynamic inclusion is unavoidable, define a strict whitelist of allowed files first:$allowed_files = ['config.php', 'utils.php', 'yourfile.php']; $requested_file = $_GET['file'] ?? ''; if (in_array($requested_file, $allowed_files)) { include $requested_file; } else { die("Invalid file request"); } - Restrict file path boundaries:Lock included files to a specific directory and use
realpath()to verify the final path doesn't escape your target folder:$safe_base_dir = __DIR__ . '/approved_includes/'; $resolved_path = realpath($safe_base_dir . $_GET['file']); if ($resolved_path !== false && str_starts_with($resolved_path, $safe_base_dir)) { include $resolved_path; } else { die("Unauthorized file access"); } - Tighten PHP config settings:Modify your
php.inito disable risky behaviors:- Set
allow_url_include = Offto block remote file inclusion attacks - Configure
open_basedirto your application's root directory, preventing access to external file systems
- Set
- Avoid dynamic inclusion entirely (when possible):Hardcode your include paths directly (like
include 'yourfile.php';) instead of using variables—this eliminates the risk at the source - Strict input sanitization:If you must handle user input, filter out all non-safe characters (like path separators
/or\) and enforce file extensions:$clean_file = preg_replace('/[^a-zA-Z0-9_]/', '', $_GET['file']); include $clean_file . '.php'; // Fix the file extension to prevent malicious suffix injection
阻止所有来自应用外部的请求
- Web server-level restrictions:
- For Nginx, restrict access to sensitive directories to local/Trusted IPs only:
location /sensitive_includes/ { allow 127.0.0.1; allow 192.168.1.0/24; // Replace with your trusted internal IP range deny all; } - For Apache, add similar rules in your
.htaccessor server config:<Directory "/var/www/html/sensitive_includes"> Require ip 127.0.0.1 Require ip 192.168.1.0/24 </Directory>
- For Nginx, restrict access to sensitive directories to local/Trusted IPs only:
- PHP-side request origin validation:Add a check at the top of your scripts to block untrusted IPs:
$trusted_ips = ['127.0.0.1', '10.0.0.0/8']; // Update with your trusted IPs/ranges $client_ip = $_SERVER['REMOTE_ADDR']; // Reject requests from public IPs not in the trusted list if (!in_array($client_ip, $trusted_ips) && filter_var($client_ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) { die("External requests are prohibited"); } - Firewall/Security Group rules:Use server firewalls (like
ufworiptables) or cloud security groups to only allow incoming traffic from your trusted IP ranges, blocking all unknown external requests.
内容的提问来源于stack exchange,提问作者user45678
相关产品推荐
相关产品推荐

