Skip to content
Language-Server SAST for Python: Catching Pickle IDOR Beyond AST Scanning (July 2026)

Language-Server SAST for Python: Catching Pickle IDOR Beyond AST Scanning (July 2026)

Gecko Security17 min read
On this page

You've probably looked at npm security news or nodejs vulnerabilities and noticed the same theme: the dangerous call is visible, but the path that made it dangerous isn't. Python pickle deserialization bugs follow the same pattern. An AST scanner sees pickle.loads(data) and either flags every instance as a false positive or misses the ones where data traveled through four helper functions before arriving. Language-server-backed analysis traces that full inter-procedural path, which is why it finds the IDOR hiding inside the reconstructed object when every other tool stopped at the call site.

TLDR:

  • Python pickle serializes executable instructions, not data; any pickle.loads() call on attacker-controlled bytes gives arbitrary code execution.
  • AST tools cannot trace taint across module boundaries in Python, so indirect pickle sinks stay invisible to file-level scanners.
  • ML pipelines amplify the risk: torch.load() without weights_only=True and Hugging Face model files execute whatever __reduce__ specifies.
  • Replace pickle with JSON, MessagePack, or safetensors for ML artifacts; any format that reconstructs arbitrary objects has an execution model and an attack surface.
  • Gecko Security traces deserialized object fields through inter-procedural call chains to detect IDOR and authorization gaps that pattern-matching cannot find.

What Python Pickle Does and Why It's Everywhere#

Python's pickle module converts Python objects into a binary byte stream and reconstructs them on the other end. Any object can be serialized: class instances, nested dictionaries, function references, even custom types with complex inheritance chains. The reconstructed object behaves identically to the original, which is what separates pickle from simpler formats.

That fidelity explains why pickle shows up across so many Python codebases. ML engineers use it to persist trained models to disk after long training runs. Task queue frameworks like Celery serialize job arguments into pickle payloads before pushing them onto Redis or RabbitMQ. Web applications reach for it in session storage and cache layers. JSON cannot handle arbitrary Python objects; pickle can, with no schema definition required. For Python developers, it is often the path of least resistance when the object being saved is too complex for anything else.

How Pickle Serialization Works Under the Hood#

At its core, pickle runs a stack-based virtual machine. Serialized data is a sequence of opcodes that the VM executes to push values onto a stack, build containers, and reconstruct the original object. pickle.dumps(obj) produces that opcode stream as bytes; pickle.loads(data) feeds it back into the VM. The file-based equivalents, pickle.dump(obj, file) and pickle.load(file), do the same against an open file handle.

Six protocols govern the opcode format. Protocol 0 is ASCII-readable. Protocols 1 and 2 added binary encoding and new-style class support. Protocol 3 introduced explicit bytes handling; protocol 4 handles large objects; protocol 5, added in Python 3.8, supports out-of-band buffer data. Higher protocols are more compact, but produce streams that older interpreters cannot parse. When you call pickle.dumps(obj), you can pass a protocol argument; if you skip it, Python picks the highest protocol your interpreter supports.

The piece that matters most for security is __reduce__ and __reduce_ex__. When pickle serializes an object that defines either method, it stores the return value, a tuple of (callable, args), in the opcode stream. On deserialization, pickle calls callable(*args) to reconstruct the object. That callable can be any importable Python function, including os.system.

Why This Makes Untrusted Pickle Data Dangerous#

The VM imposes no restrictions on which callables it will invoke. There is no allowlist, no sandbox, and no inspection step. The opcode GLOBAL instructs the VM to import a named module attribute; REDUCE invokes it with the stacked arguments. An attacker who controls the byte stream can chain those two opcodes to call any function reachable from the Python import system.

A minimal proof looks like this:

python
import pickle, os

class Exploit:
    def __reduce__(self):
        return (os.system, ("id",))

payload = pickle.dumps(Exploit())
pickle.loads(payload)  # executes: os.system("id")

No special privileges required. No vulnerable library version to target. The execution happens because pickle.loads was called on attacker-controlled bytes, full stop. That is a structural property of the format, not a bug that a patch will fix.

What Can Be Pickled and Unpickled#

Python's built-in types serialize without configuration. Integers, floats, strings, bytes, booleans, and None all pickle cleanly. Lists, tuples, sets, and dictionaries follow the same pattern, provided their contents are themselves picklable. Class instances work as long as the class is importable from the same module path at deserialization time. Functions defined at module level are picklable by reference: the opcode stream stores the module path and function name, not the bytecode itself.

Lambdas and nested functions are where things get complicated. Pickle cannot serialize them by default because they lack a stable module-level import path. Libraries like dill extend this by serializing bytecode directly, which broadens the attack surface further.

Some objects resist pickling entirely. File handles, database connections, sockets, and locks hold OS-level resources with no meaningful binary representation. Attempting to pickle them raises a TypeError.

__getstate__ and __setstate__ exist to bridge that gap. A class can define __getstate__ to return only the serializable attributes, stripping the file handle before the opcode stream is written. On the other side, __setstate__ receives that dict and rebuilds the object, reopening the connection fresh:

python
class DBSession:
    def __getstate__(self):
        state = self.__dict__.copy()
        del state['connection']  # not picklable
        return state

    def __setstate__(self, state):
        self.__dict__.update(state)
        self.connection = create_connection()  # recreate on load

The breadth of what pickle handles by default is exactly what makes it dangerous. The richer the type support, the wider the callable space an attacker can reference inside a crafted payload.

Why Pickle Is Dangerous by Design#

Python's pickle module is genuinely dangerous in a way that most serialization libraries are not. The danger is structural: pickle doesn't serialize data, it serializes executable instructions. When Python deserializes a pickle stream, it runs those instructions. There is no sandbox, no type allowlist, no validation layer between the byte stream and the interpreter.

The attack surface this creates is direct. Any application that deserializes untrusted pickle data gives an attacker arbitrary code execution. The attacker constructs a payload that calls os.system, spawns a reverse shell, or writes to disk, then delivers it wherever the application accepts pickle input: an API endpoint, a message queue, a cached model artifact, a user-uploaded file.

Why the Warning Is So Hard to Enforce#

The Python documentation warns against unpickling untrusted data, but enforcing that boundary is harder than it sounds.

  • Pickle appears throughout the Python data science ecosystem because libraries like NumPy, scikit-learn, and PyTorch use it for model serialization by default. Engineers who would never write pickle.loads(request.body) directly still call it indirectly through joblib.load or torch.load without realizing the underlying mechanism is identical.
  • Trust boundaries erode over time. A model artifact that starts as an internal file can migrate to an S3 bucket with overly permissive ACLs, a shared cache layer, or a user-facing upload endpoint, as seen in CVE-2025-54381 where file upload processing introduced a server-side request forgery path. The deserialization code never changes; the trust assumptions do.
  • Static analysis tools struggle to trace this because the call to pickle.loads may be several abstraction layers removed from the point where untrusted data enters the application. Static code analysis operates on source text, which makes inter-procedural taint paths opaque. An AST-level scanner sees a call to a safe-looking wrapper function. The taint path from HTTP request to deserializer stays invisible.

The detection difficulty scales with indirection. A scanner that traces taint inter-procedurally across library boundaries catches what file-level AST analysis cannot see.

How Pickle Deserialization Attacks Work#

When Python's pickle module deserializes data, it executes a bytecode stream that can call arbitrary Python objects. The attack surface is the __reduce__ method: any class can implement it to return a callable and a tuple of arguments, and pickle.loads() will invoke that callable unconditionally during deserialization.

Here is a minimal example of what that looks like in practice:

python
import pickle, os

class Exploit:
    def __reduce__(self):
        return (os.system, ("id",))

payload = pickle.dumps(Exploit())
pickle.loads(payload)  # executes os.system("id")

No sandbox. No validation step. The execution happens inside the deserialization call itself, before your application code has any opportunity to inspect what arrived.

Why the Sink Is Hard to Trace#

The problem for static analysis is that pickle.loads() calls are rarely adjacent to the untrusted input that feeds them. A typical exploit path looks like this:

  • A web handler reads a value from a request body, cookie, or cache layer and stores it in a variable with an innocuous name like session_data or cached_result.
  • That value passes through one or more helper functions, possibly crossing module boundaries, before reaching a background worker or a service that calls pickle.loads().
  • The call site itself looks clean: pickle.loads(data) with a local variable, no obvious user input nearby.

An AST-based scanner sees the call to pickle.loads(). It cannot follow the data back across those module boundaries to confirm whether data originates from an attacker-controlled source. The result is either a noisy false positive on every pickle.loads() call, or a tuned rule that misses the ones where the input path is indirect.

Language-server-backed analysis resolves the full inter-procedural call graph before flagging anything. The taint origin at the HTTP boundary gets traced through every intermediate assignment and function call until it reaches the sink. If the path connects, the finding includes the complete chain.

Pickle in the ML and AI Supply Chain#

Pickle's role in the AI supply chain has quietly become one of the more consequential serialization risks in production engineering. When data scientists export trained models, pickle and its variant cloudpickle are the default choice across PyTorch, Hugging Face, and most MLflow-backed experiment pipelines. The format is convenient: it preserves arbitrary Python objects, including lambdas, closures, and custom class instances that JSON or Protobuf cannot capture.

The problem is structural. Pickle deserializes by executing Python bytecode, and that bytecode can call any importable function. A model artifact is, from a security standpoint, an executable. Loading one from an untrusted source is equivalent to running arbitrary code with the permissions of the process doing the loading.

Why the AI Pipeline Amplifies the Risk#

The threat surface here is wider than most teams account for, across the ML supply chain:

  • Model registries like Hugging Face Hub host hundreds of thousands of pickle-format files, and any contributor can publish one. Downloading a model for fine-tuning and calling torch.load() on it without weights_only=True executes whatever the file's __reduce__ method specifies.
  • CI/CD pipelines that pull pretrained weights as build artifacts inherit this risk automatically, similar to RCE in your test suite via injected agent skills. A poisoned model checkpoint inserted into a shared registry propagates to every downstream training run that consumes it.
  • cloudpickle, used heavily in distributed compute frameworks like Ray and Dask, serializes closures sent to worker nodes. A compromised scheduler or shared task queue can inject malicious payloads into worker processes across an entire cluster.

Python's typing system offers no protection here. The pickle.loads() call accepts bytes, and what those bytes instruct the interpreter to do is invisible until execution. Static tools that read only the AST see a call to a known function with a variable argument. Without tracking where that bytes object originated, no AST-level tool can determine whether the payload is safe, a gap documented in the Picklescan RCE advisory, where malicious pickle files bypassed static analysis entirely.

Secure Alternatives to Pickle#

When pickle's risks outweigh its convenience, the alternatives fall into a few clear categories depending on what you're actually serializing.

JSON covers most use cases where the data fits primitive types: strings, numbers, booleans, lists, dicts, and None. It has no execution model. json.loads() cannot call os.system regardless of what you put in the string. Cross-language support is as good as it gets, and the format is human-readable. The tradeoff is type fidelity: custom class instances need explicit serialization logic, and binary data requires base64 encoding.

MessagePack gives you binary-efficient encoding with the same execution-free guarantee. It handles the same type set as JSON but compresses better, which matters when you're serializing high-throughput message queue payloads. Python's msgpack library is a straightforward drop-in for scenarios where JSON is too verbose.

YAML deserves a specific warning: yaml.load() has historically allowed arbitrary Python object construction, mirroring pickle's problem. Always use yaml.safe_load(). The safe variant restricts deserialization to YAML's built-in types and raises an error on anything that would require executing Python code.

marshal is CPython-internal and intentionally limited. It serializes Python code objects, not arbitrary class instances, and the documentation explicitly states it's not secure against malformed data. Treat it as off-limits for anything that touches user input.

See it in action.

The pattern worth internalizing: any format that reconstructs arbitrary objects needs an execution model to do it, and an execution model is an attack surface. If you find yourself needing pickle's type breadth for ML artifacts, PyTorch's weights_only=True flag in torch.load() and the safetensors format from Hugging Face are purpose-built alternatives that strip the callable machinery entirely.

Where SAST Fits Into This#

Switching formats removes the risk at the source, but understanding SAST vs DAST helps teams choose the right tool for each layer. Codebases accumulate pickle usage over time, often buried in caching layers, job queues, or model-serving pipelines where the original author is long gone. That's where static analysis earns its place, though the quality of that analysis varies considerably.

AST-based scanners can flag calls to pickle.loads() and pickle.load() when the argument is identifiable as external input within the same file. The problem is that Python's type system gives those tools almost nothing to work with across module boundaries. A request.body that gets passed through three utility functions before reaching the deserializer looks, to an AST parser, like a generic object. The taint trace stops at the first function call that crosses a file boundary, a core reason static analysis struggles with business logic.

Language-server-backed analysis resolves this by building a semantic graph that mirrors what the Python interpreter actually knows: which type a variable holds at each call site, which methods are available on it, and which module originally produced the value. Gecko's analysis operates at this level, tracing untrusted input through inter-procedural call chains to dangerous sinks regardless of how many abstraction layers separate the entry point from the pickle.loads() call. The finding includes a proof-of-concept showing the exact code path, not a pattern match that guessed at the flow.

Why AST-Based SAST Tools Struggle to Detect Pickle Misuse in Python#

Python's type system creates a structural problem for static analysis tools. Because types are resolved at runtime instead of declared in source code, an AST-based scanner reading a .py file sees variable names and call sites, but cannot know with confidence what type a given object will carry when the program actually runs.

For pickle misuse in particular, this matters in a concrete way. The dangerous surface is pickle.loads() called on attacker-controlled input. An AST tool can pattern-match that call site. What it cannot do is trace the provenance of the argument across module boundaries, through assignment chains, or into objects that were passed through a web framework's request handling layer.

Where the Type Resolution Gap Becomes an Exploitable Blind Spot#

Consider a typical Flask application where request data enters through one module, gets stored in a cache layer, and is later deserialized in a separate service handler. The AST of any single file in that chain looks clean. The call to pickle.loads() exists in a file that never directly imports flask.request. The tainted data arrives as a plain bytes argument with no annotation.

Three structural limitations combine here:

  • AST tools operate on a per-file or per-module basis and cannot follow a value across the module graph without type information anchoring the traversal.
  • Python's duck typing means a parameter named data in a deserializer function could legally receive any object, and the AST carries no information about which caller will supply attacker-controlled bytes.
  • Decorator-based routing in frameworks like Flask and FastAPI means the entry point connecting an HTTP handler to a deserialization function often exists only at runtime, invisible to static parse trees.

Language-server-backed analysis resolves this by building a semantic graph that mirrors what a compiler or interpreter would construct: type inference propagates across call boundaries, import graphs are walked to their leaves, and framework decorators are resolved to their actual routing behavior. The result is that a tainted pickle.loads() call becomes traceable back to its HTTP entry point even when no single file contains both ends of the path.

This is the same gap that lets IDOR vulnerabilities survive AST-based scanning in Python codebases, a pattern covered in depth in business logic as AppSec's unsolved problem. The authorization check and the resource access exist in different files. Without cross-boundary type resolution, no tool reading ASTs can confirm whether the object reaching the access point carries the identity of the requesting user or an arbitrary identifier supplied by that user.

How Language-Server-Backed Analysis Resolves Types Across Python Codebases#

Language servers were built to give IDEs accurate, real-time type information. Tools like Pylance and Jedi resolve imports, track type narrowing across branches, and follow attribute access chains through inheritance hierarchies. When a security analysis engine hooks into that same resolution machinery, it gets the same picture the compiler gets.

The practical consequence: when a request parameter flows into a function that the language server resolves to return a User object, the analysis knows the downstream .id access is a database row identifier, not an arbitrary string. AST tools see a function call followed by attribute access. The language server sees the full type chain.

Why This Matters for IDOR Detection#

IDOR vulnerabilities follow a recognizable pattern: a user-controlled identifier reaches a resource lookup without an ownership check intercepting the path. Catching that pattern requires knowing what each variable actually holds at each step.

  • When Python reassigns a variable mid-function or narrows its type through a conditional, a language-server-backed engine tracks the updated type through every branch, so it does not conflate the pre-check and post-check states of an object.
  • When a resource object comes from a third-party ORM, the engine resolves its schema from installed package stubs, giving it accurate field-level knowledge of what .owner_id or .created_by actually references, the same kind of taint awareness needed to catch SQL injection via ORM queries.
  • When authorization logic lives in a decorator on a parent class, the engine walks the method resolution order to confirm whether that guard runs for the specific route being analyzed.

The result is that a finding like "user-controlled order_id reaches Order.objects.get() without a .user ownership filter" is grounded in verified type information at every hop, not a pattern match against variable names that happen to look like identifiers.

How Pickle IDOR Slips Past Pattern Matching#

Python's pickle module is where runtime typing's security implications become concrete. When a web endpoint deserves an object ID from a pickled payload, a static AST scanner sees the deserialization call. It does not see that the user_id field inside the unpickled object flows directly into a database query with no ownership check. The type of that field is unknown at parse time, so the scanner cannot follow the data.

The gap is structural. AST tools read tokens and tree nodes. They do not resolve what pickle.loads() returns, because Python's type system makes that unknowable without executing the code or consulting a language server that tracks inferred types across the call graph.

Why the Call Graph Is the Missing Piece#

A language-server-backed analyzer maintains a semantic model of the codebase. When it sees obj = pickle.loads(data), it queries the inferred return type, traces obj.resource_id through every downstream call frame, and checks whether an authorization gate appears anywhere in that chain before the value reaches a query sink.

Consider a typical pattern:

python
def get_resource(request):
    obj = pickle.loads(request.body)
    return Resource.objects.get(id=obj.resource_id)

The IDOR here has no syntax signal. No missing if, no obvious taint source a regex could match. Those are the same blind spots that make securing AI-generated code especially difficult when models emit pickle-heavy patterns. The authorization failure lives in what the code omits across multiple frames, not in what it contains in any single file. AST scanners match patterns that exist. Language-server analysis can reason about patterns that are absent.

Gecko Security: Language-Server Analysis Applied to Pickle and Authorization Gaps#

Where AST tools see request.user.id and assume the attribute is trustworthy because the name looks right, Gecko traces the full construction path: the deserialization call, the middleware that populated the field, and whether any authorization check actually ran on that value before it reached the database query. The mechanism is language-server-backed analysis that resolves Python's type ambiguity at the call site, not at the pattern level.

For pickle-based deserialization, this matters in a specific way, as shown in Gecko's published vulnerability research. Python pickle vulnerabilities often surface not in the loads() call itself but in what happens to the reconstructed object afterward. If a deserialized object's fields flow into an access-control decision without re-validation, the IDOR exists regardless of whether the pickle call was flagged. Language-server resolution lets Gecko follow that object across module boundaries, tracking whether the reconstructed value ever passes through a trust boundary check.

The same inter-procedural tracing applies to Node.js and Go codebases. In Node.js, where npm package chains can introduce implicit type coercions, Gecko resolves what a variable actually holds at each call site. In Go, where type assertions can silently fail or return zero values, Gecko tracks whether authorization logic ever sees the intended concrete type, a capability that separates it from the best AI-powered security testing tools in the field.

What This Catches That AST Tools Miss#

Vulnerability ClassAST Tool BehaviorLanguage-Server Analysis
IDOR via deserialized object fieldsFlags the pickle.loads() call; misses downstream access logicTraces reconstructed object fields to authorization check presence or absence
Cross-module authorization bypassSees the function call; cannot resolve what the callee does with the valueResolves the full call chain across file and package boundaries
Node.js implicit coercion in auth checksPattern-matches the check structure; misses type mismatch at runtimeResolves the actual type flowing into the comparison
Go zero-value authorization failureNo visibility into type assertion outcomesTracks failed assertions and whether zero-value branches reach protected resources

Final Thoughts on Pickle Serialization, Deserialization Attacks, and SAST Gaps#

If your code loads pickle data from any source outside your direct control, the risk isn't theoretical. The callable machinery in pickle's VM gives an attacker arbitrary code execution by design, and no version bump will change that. Safer formats solve it upstream; inter-procedural static analysis catches it where the format can't be swapped out. Talk to the Gecko team to see how taint tracing across module boundaries surfaces these paths in practice.

FAQ#

Why does Python's runtime type resolution make pickle vulnerabilities so hard to detect with standard SAST tools?#

AST-based scanners read tokens and tree nodes, but Python resolves types at runtime. When a bytes object flows through three utility functions before reaching pickle.loads(), no AST parser can confirm whether those bytes originated from an attacker-controlled HTTP request or a trusted internal source. The taint trace stops at the first function call that crosses a file boundary, leaving the full exploit path invisible.

What's the best way to handle Python pickle security in ML pipelines?#

Replace pickle with purpose-built alternatives where possible: PyTorch's weights_only=True flag in torch.load() strips the callable machinery that makes deserialization dangerous, and Hugging Face's safetensors format removes it entirely. For codebases where pickle is already embedded in caching layers or job queues, language-server-backed static analysis can trace tainted input through inter-procedural call chains to the pickle.loads() sink, catching what file-level pattern matching misses.

How do I detect IDOR vulnerabilities introduced through deserialized pickle objects?#

The IDOR signal has no syntax marker: there is no missing if statement a regex can match, and the authorization failure lives in what the code omits across multiple frames. A language-server-backed analyzer traces the reconstructed object's fields through every downstream call frame and checks whether an authorization gate appears anywhere in that chain before the value reaches a query sink, giving you the complete path instead of a pattern match that guessed at the flow.

Pickle vs. safetensors for ML model serialization: which should I use?#

Use safetensors for any model artifact that crosses a trust boundary, including downloads from public registries like Hugging Face Hub. Pickle serializes executable instructions, so loading a pickle-format model from an untrusted source is equivalent to running arbitrary code with the permissions of the loading process. safetensors stores only tensor data with no execution model, so there is no callable machinery for a poisoned checkpoint to invoke.

Can static analysis catch indirect pickle.loads() calls routed through libraries like joblib or torch.load()?#

Yes, if the analysis builds a full inter-procedural call graph. AST-based tools see a call to a safe-looking wrapper and stop there. Language-server-backed analysis resolves the full call chain into the library, confirms that joblib.load() or torch.load() (without weights_only=True) invokes pickle.loads() internally, and traces whether the argument to the outer call originated from an attacker-controlled source, producing a finding with the complete path from HTTP entry point to deserializer sink.

Gecko Security

Frequently asked questions

Related content

The latest news, technologies, and resources from our team.

Subscribe to the Gecko newsletter

Occasional updates, new content, and insights. No spam; unsubscribe anytime.

We use your email only to send you our newsletter. See our privacy policy for how we handle your data. You can unsubscribe at any time.