XXE in Go (encoding/xml)
Go encoding/xml XXE attacks do not work against the standard library: encoding/xml tokenises directives but never resolves external entities or loads DTDs, so file-read and SSRF via XXE are not possible — the caveats are third-party cgo bindings to libxml and basic entity-expansion limits.
Go's standard encoding/xml package was designed without external entity resolution. It parses <!DOCTYPE> and <!ENTITY> as directive tokens but does not fetch external resources or substitute external entities, so the classic XXE attack surface is absent. Exposure only appears if you bring in a cgo wrapper around libxml2 or custom-handle entities.
Secure parser configuration
encoding/xml (standard library)
import "encoding/xml"
var v Payload
// encoding/xml does not resolve external entities or load DTDs.
if err := xml.Unmarshal(untrusted, &v); err != nil {
// handle
}No external entity resolution exists to disable — the stdlib is XXE-safe by design.
Custom Decoder (bound input size)
dec := xml.NewDecoder(io.LimitReader(r, maxBytes))
// Optionally restrict charset handling:
dec.CharsetReader = nil // reject unknown charsets rather than fetching
for {
tok, err := dec.Token()
if err == io.EOF { break }
if err != nil { /* handle */ break }
_ = tok
}Limit input size and leave CharsetReader nil unless you control the charset source.
Common pitfalls that re-introduce XXE
- Introducing a cgo libxml2 binding and enabling its entity/DTD options.
- Writing a custom entity resolver that fetches external resources.
- Not bounding request body size (large documents can still be a DoS).
- Assuming other languages' XXE payloads will behave the same in Go — they will not.
Verifying the fix
Send a classic XXE file-read payload: with encoding/xml the entity is not expanded and no file is read. Verify any third-party XML dependency does not wrap libxml with entity resolution enabled, and that request bodies are size-limited.