Catalog My learning Blog
Application Security for Developers: Secure Coding Course · Phase 2 · Lesson 13 · 4 min read

XXE and Insecure Deserialization Attacks

On this page
  1. When parsing means executing
  2. XXE: XML external entities that read your files
  3. Insecure deserialization: data that runs code
  4. Check yourself

When parsing means executing

Developers think of parsing as reading data. Two formats break that assumption: XML with external entities, and native object serialization. Both let attacker-supplied input make your application read files or run code.

XXE: XML external entities that read your files

XML lets a document define entities, shortcuts that expand to other content, including the contents of a file or URL. If the parser resolves them, an attacker can send:

HTML
<?xml version="1.0"?>
<!DOCTYPE order [ <!ENTITY xxe SYSTEM "file:///srv/app/secret.txt"> ]>
<class="tok-k">order><class="tok-k">note>&xxe;</class="tok-k">note></class="tok-k">order>

And the file's contents appear wherever the application uses note, perhaps echoed in a response. Parsed three ways in Python, with a test file containing a fake secret:

Code
unsafe = ET.XMLParser(resolve_entities=True, no_network=True)
ET.fromstring(payload, unsafe)        # lxml with entity resolution turned on
ET.fromstring(payload)                # lxml 6 defaults
defusedxml.ElementTree.fromstring(payload)
Code
lxml 6.1.3
resolve_entities=True : TOP SECRET: db password is hunter2
lxml defaults         : XMLSyntaxError Entity 'xxe' not defined, line 3, column 19
defusedxml            : EntitiesForbidden EntitiesForbidden(name='xxe', system_id='file:///.../secret.txt', public_id=None)

With resolution on, the file is read. Recent lxml versions refuse external entities by default, and defusedxml rejects the document outright. Older libraries and some Java and .NET parsers resolved external entities by default, which is why XXE was common. XXE can also reach internal URLs (SSRF, Day 12) and exhaust memory with nested entities ("billion laughs").

Defenses: disable DTDs and external entities in your parser (OWASP's XXE Prevention Cheat Sheet lists the settings per language), use defusedxml in Python, keep parsers updated, and prefer JSON where you control the format.

An XML parser that resolves external entities reads local files into the document; a native deserializer reconstructs objects by calling whatever the payload names.
An XML parser that resolves external entities reads local files into the document; a native deserializer reconstructs objects by calling whatever the payload names.

Insecure deserialization: data that runs code

Native serialization formats (Python's pickle, Java serialization, .NET's BinaryFormatter, PHP's unserialize) save and restore objects, including instructions for how to rebuild them. An attacker who controls the bytes controls those instructions:

Python
import pickle, json

class Exploit:
    def __reduce__(self):              # tells pickle how to "rebuild" the object
        import os
        return (os.system, ("echo '>>> code ran during pickle.loads'",))

blob = pickle.dumps(Exploit())         # what an attacker would send as a "session cookie"
pickle.loads(blob)                     # the command runs here, before any type check
json.loads(blob)                       # JSON can only produce data
Code
payload bytes: 74
>>> code ran during pickle.loads
json.loads: UnicodeDecodeError

74 bytes, and the server runs a shell command of the attacker's choosing. Real exploits use the classes already on the classpath ("gadget chains"); Java deserialization flaws in widely used libraries led to many remote code execution vulnerabilities.

Defenses:

  • Never deserialize untrusted data with native formats. Use JSON, Protocol Buffers or similar data-only formats, and validate against a schema.
  • If you must accept serialized objects, sign them (HMAC, Day 17) and verify before deserializing, and use type allow-lists.
  • Microsoft removed BinaryFormatter from .NET 9 for this reason; Python's documentation warns never to unpickle untrusted data.
  • Watch for hidden deserialization: session stores, caches, message queues and "remember me" cookies.

Check yourself

Make the parser read local files, like /etc/passwd, or fetch internal URLs and include their content in the parsed document, which may be returned to the attacker. Some parsers can also be pushed into consuming huge amounts of memory.

Pickle can instruct the loader to call arbitrary functions while it rebuilds objects, so attacker code runs during deserialization, before your type check ever executes. The same applies to Java native serialization and similar formats.

Use data-only formats like JSON with schema validation, which can't trigger code or file access when parsed, and configure any XML parsers to reject DTDs and external entities. Avoid native object serialization formats for untrusted input entirely.

Turn off DTD processing and external entity resolution in the parser's settings. In Python, defusedxml provides safe parsers by default.

Sign the data with an HMAC so only data you produced is accepted, and restrict which classes may be loaded.