XXE(XML External Entity)攻击是一种针对XML处理器的安全威胁,攻击者通过构造恶意XML文档,利用外部实体声明来读取服务器上的敏感文件或发起服务端请求伪造(SSRF)攻击。以下是保护Linux服务器Web接口免受XXE攻击的综合方案:
// PHP示例
libxml_disable_entity_loader(true);
# Python lxml示例
from lxml import etree
parser = etree.XMLParser(resolve_entities=False)
// DocumentBuilderFactory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
# 在server配置中添加
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header X-Frame-Options "SAMEORIGIN";
# 在httpd.conf或虚拟主机配置中添加
Header set X-Content-Type-Options "nosniff"
Header set X-XSS-Protection "1; mode=block"
Header set X-Frame-Options "SAMEORIGIN"
// Node.js示例
const sax = require('sax');
const parser = sax.parser(false, {strictEntities: true});
# 确保敏感文件权限正确
sudo chmod 600 /etc/passwd /etc/shadow
sudo chown root:root /etc/passwd /etc/shadow
# 检查SELinux状态
getenforce
# 如果禁用,可启用
sudo setenforce 1
sudo sed -i 's/SELINUX=disabled/SELINUX=enforcing/g' /etc/selinux/config
# 监控可疑的XML请求
sudo grep -i "<!ENTITY" /var/log/nginx/access.log
# 在/etc/fail2ban/filter.d/xxe.conf中添加
[Definition]
failregex = <!ENTITY.*SYSTEM.*>
# 定期更新系统
sudo apt update && sudo apt upgrade -y # Debian/Ubuntu
sudo yum update -y # RHEL/CentOS
SecRule REQUEST_HEADERS:Content-Type "application/xml" \
"id:'100000',phase:1,t:none,block,msg:'Potential XXE Attack',\
chain"
SecRule REQUEST_BODY "@contains <!ENTITY" \
"t:none,setvar:tx.xxe_score=+1"
通过实施以上多层次防御措施,可以显著降低Linux服务器Web接口遭受XXE攻击的风险。建议定期进行安全审计和渗透测试,确保防护措施的有效性。