XML外部实体(XXE)防护与安全解析最佳实践概述不安全的XML解析可能导致外部实体访问与信息泄露。通过禁用DTD与外部实体、严格字段白名单可防护。安全解析示例import { DOMParser } from 'xmldom'
function parseXmlSafe(input: string): Document | null {
if (input.length > 1000000) return null
const parser = new DOMParser({ errorHandler: () => {} })
const doc = parser.parseFromString(input, 'text/xml')
const dtd = doc.doctype
if (dtd) return null
const pi = doc.getElementsByTagName('?xml')
return doc
}
字段白名单与提取function extractFields(doc: Document, allow: string[]): Record<string, string> {
const out: Record<string, string> = {}
for (const name of allow) {
const nodes = doc.getElementsByTagName(name)
const val = nodes.item(0)?.textContent || ''
out[name] = val
}
return out
}
运维要点禁用DTD与外部实体,限制输入大小与资源访问采用字段白名单进行提取与校验,拒绝未知节点在审计中记录解析失败与异常结构来源通过禁用DTD与外部实体、白名单提取的组合,可在后端形成稳健的XXE防线。

发表评论 取消回复