Description
Keep Foundation’s protective defaults for untrusted XML. XMLParser defaults shouldResolveExternalEntities to false. Where available, externalEntityResolvingPolicy defaults to .never. External resource access depends on this policy and the XMLParserDelegate implementation.
Potential impact
Loading external entities can expose files or trigger network requests even when the result stays out of a response. Large DTDs and excessive entity expansion can consume memory and CPU.
Remediation
- Before
parse(), keepshouldResolveExternalEntitiesatfalseand, where supported,externalEntityResolvingPolicyat.never. Check later configuration and delegates for external loads. The.noNetworkpolicy can still allow local resources. - If a trusted workflow needs external entities, handle it separately and allow only preapproved entity URLs. Limit input size and processing time, too.
Examples
Before
swift
import Foundation
func parseRemoteXML() throws {
let remoteData = try Data(
contentsOf: URL(string: "https://example.com/input.xml")!
)
let parser = Foundation.XMLParser(data: remoteData)
parser.externalEntityResolvingPolicy = .always
parser.shouldResolveExternalEntities = true
_ = parser.parse()
}
After
swift
import Foundation
func parseRemoteXML() throws {
let remoteData = try Data(
contentsOf: URL(string: "https://example.com/input.xml")!
)
let parser = Foundation.XMLParser(data: remoteData)
parser.externalEntityResolvingPolicy = .never
parser.shouldResolveExternalEntities = false
_ = parser.parse()
}
Both examples first fetch the XML document with Data(contentsOf:). The .never policy limits external entities during parsing. Check the URL of the initial download separately.