在Ubuntu上设置PHP的安全性是非常重要的,以下是一些关键步骤和最佳实践:
确保系统和所有软件包都是最新的,以修复已知的安全漏洞。
sudo apt update
sudo apt upgrade
安装并配置Apache或Nginx,并确保使用HTTPS来加密数据传输。
sudo apt install apache2
sudo a2enmod ssl
sudo systemctl restart apache2
编辑PHP的配置文件 php.ini
,进行以下设置:
错误报告:在生产环境中,关闭详细的错误报告,只显示必要的信息。
display_errors Off
log_errors On
error_reporting E_ALL & E_NOTICE & E_DEPRECATED & E_STRICT & E_USER_NOTICE & E_USER_WARNING
安全模式:启用安全模式,并限制可以执行的类。
safe_mode On
safe_mode_allowed_classes "mysqli,pdo_mysql"
禁用危险函数:禁用不需要的PHP函数,如 exec()
,system()
等。
disable_functions exec,system,passthru,shell_exec,popen,curl,fsockopen,file_get_contents,mkdir,rmdir,rename,unlink,chmod,chown,chgrp,date,time,localtime,gmtime,isset,empty,is_array,is_object,is_resource,is_string,is_int,is_float,is_bool,is_callable,assert
文件系统限制:使用 open_basedir
限制PHP可以访问的系统目录。
open_basedir /var/www/html:/tmp
禁止远程资源访问:关闭 allow_url_fopen
和 allow_url_include
。
allow_url_fopen Off
allow_url_include Off
上传权限:限制文件上传功能,防止恶意文件上传。
location /(uploads|assets)/.*\.(php|php5|jsp) {
deny all;
}
使用UFW(Uncomplicated Firewall)限制访问特定端口,保护服务器免受恶意攻击。
sudo ufw enable
sudo ufw allow 'Apache Full'
sudo ufw allow 'OpenSSH'
定期检查并更新你的项目依赖库,以确保它们没有已知的安全漏洞。
composer update
使用诸如 PHP Security Advisories Checker 之类的工具来扫描你的代码,查找潜在的安全问题。