Skip to content
Wednesday, October 21, 2026AboutContactRSS
Stop Python Pickle Deserialization Attacks with These 3 Fixes
Vulnerabilities

Stop Python Pickle Deserialization Attacks with These 3 Fixes

Python pickle executes arbitrary code during deserialization, turning trusted data sources into direct paths for remote code execution on your server.

Quick answer

Never deserialize untrusted data with pickle. Replace it with JSON, MessagePack, or Protocol Buffers for data interchange. If you must use pickle, wrap it in a sandboxed process with strict timeouts and resource limits to contain any code execution that occurs.

Why Pickle Is Inherently Unsafe for Untrusted Data

Python pickle is not a safe data serialization format. It was designed to serialize Python objects for internal use, not for secure data exchange. When you call pickle.loads(), the interpreter does not just read data. It executes instructions embedded in the byte stream. These instructions can instantiate classes, call methods, and import modules. This means an attacker can craft a pickle payload that runs any code your server is capable of running. The risk exists because the format trusts the data source implicitly. You cannot separate the data from the execution logic. This design choice creates a direct path from input to code execution.

Infographic: Stop Python Pickle Deserialization Attacks with These 3 Fixes. Pickle executes arbitrary Python code during the loading process, making it unsafe for any data from external users. Standard validation or sanitization does not stop pickle attacks because the format contains executable opc
Infographic: Stop Python Pickle Deserialization Attacks with These 3 Fixes. Free to share with a link to NetSec Observer.

The Reality of "Safe" Subclasses and Validators

Many developers attempt to mitigate this risk by creating a custom unpickler class. This subclass overrides the find_class method to restrict which modules and classes can be imported. The idea is to whitelist safe types like strings, lists, and dictionaries. This approach fails in practice. Python has many built-in classes that can lead to code execution when combined. For example, the os module is often restricted, but attackers can use subprocess or importlib if those are not explicitly blocked. Maintaining a comprehensive blacklist is impossible. New attack vectors appear as the standard library evolves. This method gives a false sense of security. It reduces the attack surface slightly but does not eliminate the fundamental flaw.

Replacing Pickle with Safe Serialization Formats

The most effective prevention is to stop using pickle for data interchange. JSON is the standard alternative for most web applications. It supports basic data types like strings, numbers, arrays, and objects. It does not support functions or class instances, which eliminates the execution risk. If you need to serialize complex Python objects, consider MessagePack or Protocol Buffers.

These formats are binary, faster, and strictly data-oriented. They do not execute code during deserialization. You must map your Python objects to and from these formats manually. This requires more initial development effort. It ensures that no executable code can hide in your data streams. This change removes the risk entirely.

Sandboxing as a Last Resort

If you cannot replace pickle, you must isolate the deserialization process. Run the unpickling code in a separate process with limited privileges. Use a sandbox environment that restricts file system access and network connectivity. Set strict timeouts for the deserialization operation. If the process hangs or consumes too much memory, terminate it immediately.

This containment strategy limits the damage if an attacker succeeds. The malicious code runs, but it cannot access sensitive files or exfiltrate data. It cannot establish a reverse shell. This approach accepts that code execution will happen. It focuses on limiting the impact rather than preventing the execution. This is a defensive control, not a preventive one.

What Does Not Work for Prevention

Several common measures do not protect against pickle deserialization attacks. Input validation that checks for specific strings or patterns is ineffective. The pickle format is binary and opaque. You cannot scan for malicious intent without parsing the entire stream, which triggers the execution. Hashing the data before deserialization does not help.

The hash verifies integrity, not safety. An attacker can modify the payload and recalculate the hash. Authentication tokens ensure the request comes from a known source, but they do not prevent the source from being compromised. If an attacker controls the authenticated source, they can send malicious pickle data. Trusting the source does not equal trusting the content.

MeasureEffortWhat it stops
Replace with JSONMediumAll code execution risks
SandboxingHighDamage from successful attacks
Custom UnpicklerLowSimple, obvious attack vectors
Input ValidationLowNothing related to execution
Data HashingLowNothing related to execution

Handling Legacy Systems and Dependencies

Many older applications rely on pickle for caching or session storage. These systems are difficult to modify quickly. You must treat these components as high-risk assets. Implement external attack surface scanning to identify exposed endpoints that accept pickle data. Ensure that these endpoints are not accessible from the public internet. Use network segmentation to isolate these services. Monitor for unusual process spawns or file modifications on these servers. This monitoring helps detect successful attacks early. You should plan a migration path to safe formats. This migration may require refactoring core application logic. Prioritize this work based on the exposure level.

Integrating with Broader Security Practices

Preventing pickle attacks is part of a larger security strategy. You must also address other common vulnerabilities. For instance, broken access control can allow unauthorized users to reach the deserialization endpoint. Server-side request forgery (SSRF) can be combined with pickle attacks to target internal services. Exposure management helps you identify where your pickle endpoints are visible to the internet. Regularly review your dependencies for known issues. Some libraries may introduce pickle usage without your knowledge. Audit your codebase for import pickle statements. Replace them where possible. This holistic approach reduces the overall risk profile.

Immediate Action Checklist

You can take three steps today to reduce your risk. First, audit your code for pickle.loads() calls. Identify which ones process external data. Second, replace these calls with JSON or a safe alternative. If replacement is not possible, implement sandboxing. Third, ensure that your endpoints are not publicly accessible. Use authentication and network restrictions to limit access. Monitor your servers for unusual activity. This monitoring helps you detect attacks that bypass your controls. These steps provide immediate protection while you plan long-term fixes.

Key takeaways

  • Pickle executes arbitrary Python code during the loading process, making it unsafe for any data from external users.
  • Standard validation or sanitization does not stop pickle attacks because the format contains executable opcodes rather than just data values.
  • Switching to JSON or Protocol Buffers eliminates the execution risk entirely while maintaining structured data compatibility.
Bottom line

Pickle deserialization executes code, so you must never use it for untrusted data. Replace pickle with JSON or sandbox the process immediately to prevent remote code execution.

Frequently asked questions

Can I use pickle for data stored in my own database?

Yes, if the database is strictly controlled and never exposed to external input, pickle is safer. However, JSON is still preferred for clarity and safety.

Does encrypting pickle data make it safe?

No, encryption protects confidentiality, not integrity or safety. If an attacker can decrypt the data, they can still execute the embedded code.

How do I detect a pickle deserialization attack?

Monitor for unexpected process spawns, file modifications, or network connections from your application server. These are signs of code execution.

Is there a safe version of pickle?

No, pickle is inherently unsafe for untrusted data. There is no built-in safe mode that prevents all code execution vectors.

How this guide was produced: written by the NetSec Observer editorial team with AI assistance, checked against the public references listed below, and reviewed when the facts change. See our editorial policy or report an error.

Further reading

  1. FIRST: Common Vulnerability Scoring System
  2. MITRE CWE
  3. CISA Known Exploited Vulnerabilities Catalog
Python pickle deserializationpython securitydeserializationcode execution

Related stories