Swift Foundation XML External Entities (XXE)

Swift Foundation XML external entities (XXE)

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(), keep shouldResolveExternalEntities at false and, where supported, externalEntityResolvingPolicy at .never. Check later configuration and delegates for external loads. The .noNetwork policy 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.

References