目录遍历攻击(Path/Directory Traversal)是Web应用中常见的安全威胁,攻击者通过操纵文件路径访问服务器上的敏感文件。以下是针对Linux服务器Web接口的防护方案:
// PHP示例 - 过滤../等路径字符
$filename = basename($_GET['file']);
$filepath = '/var/www/safe_dir/' . $filename;
// Java示例
String sanitized = Paths.get("/safe/base/dir",
request.getParameter("file"))
.normalize()
.toString();
if (!sanitized.startsWith("/safe/base/dir")) {
throw new SecurityException("Invalid path");
}
location ~* \.(php|pl|py|jsp|asp|sh|cgi)$ {
deny all;
return 403;
}
location / {
# 禁止访问隐藏文件
location ~ /\. {
deny all;
}
# 限制访问特定目录
try_files $uri $uri/ =404;
}
<Directory "/var/www/html">
Options -Indexes
AllowOverride None
Order allow,deny
Allow from all
<FilesMatch "\.(htaccess|htpasswd|ini|log|sh|sql)$">
Order Allow,Deny
Deny from all
</FilesMatch>
</Directory>
# 设置Web目录适当权限
sudo chown -R www-data:www-data /var/www/html
sudo chmod -R 750 /var/www/html
# 敏感文件保护
sudo chmod 600 /etc/passwd /etc/shadow
sudo chattr +i /etc/passwd /etc/shadow
PHP配置 (php.ini):
open_basedir = "/var/www/html:/tmp"
disable_functions = "exec,passthru,shell_exec,system"
allow_url_fopen = Off
allow_url_include = Off
使用Web应用防火墙(WAF):
SecRule REQUEST_URI "@contains ../" "id:1001,deny,msg:'Directory Traversal Attempt'"
# 查找可写的Web目录文件
find /var/www/html -type f -perm -o+w -ls
# 检查SUID/SGID文件
find / -type f \( -perm -4000 -o -perm -2000 \) -exec ls -l {} \;
# 使用lynis进行安全扫描
sudo lynis audit system
通过以上多层防护措施,可以显著降低目录遍历攻击的风险,保护服务器上的敏感数据不被非法访问。