Insecure deserialization is a software vulnerability that occurs when an application reconstructs an object from untrusted data without adequately verifying what the data contains or what the resulting object is allowed to do.
Applications serialize data when they convert an object or application state into a format that can be stored or transmitted. They deserialize it when they convert that representation back into an object the program can use.
Serialization itself is not a vulnerability. The danger appears when an attacker can modify serialized data and the application trusts the reconstructed object.
A successful attack may allow someone to:
- Change application data
- Alter prices or account balances
- Impersonate another user
- Increase their privileges
- Bypass business rules
- Access unauthorized information
- Consume excessive server resources
- Execute unintended application functions
- Run code on the server in severe cases
MITRE classifies this weakness as CWE-502: Deserialization of Untrusted Data. The definition covers software that reconstructs untrusted data without adequately ensuring the resulting object is valid. MITRE’s CWE-502 entry documents the weakness.
What Are Serialization and Deserialization?
Serialization converts an in-memory object into a representation suitable for storage or transmission.
The serialized information may be placed in:
- A database
- A file
- A browser cookie
- A session token
- A cache
- An API message
- A message queue
- A mobile application request
- A URL parameter
- A background job
- A distributed service
- Cloud storage
Deserialization reverses the process. It recreates an object from that stored or transmitted representation.
For example, an e-commerce application might serialize information about a shopping cart so it can restore the cart later. A distributed system might serialize a task before placing it on a queue for a background worker.
The risk depends heavily on the format and deserialization mechanism. A simple JSON parser that creates a limited data structure behaves differently from a native object deserializer capable of creating arbitrary classes and triggering application methods.
How Does Insecure Deserialization Work?
A typical insecure deserialization attack follows this pattern:
- The application creates or accepts serialized data.
- The serialized value contains object properties, class information, or application state.
- The attacker obtains or influences that value.
- The attacker changes its content or supplies a newly constructed serialized object.
- The application deserializes the value without sufficient validation.
- The reconstructed object contains attacker-controlled state or behavior.
- The application trusts or acts on the object.
The attack may be as simple as changing a field that controls a discount. More dangerous cases may cause the deserializer or application to invoke unintended methods during object reconstruction.
OWASP’s guidance emphasizes that deserializing untrusted data can create several attack paths and should be avoided where possible. OWASP’s Deserialization Cheat Sheet provides recommendations for commonly affected platforms.
Why Is Insecure Deserialization Dangerous?
Deserialization occurs deep inside application logic. By the time the reconstructed object is used, other parts of the system may assume it came from trusted application code.
An attacker may therefore cross the boundary between external data and internal program state.
Potential consequences include:
- Authentication bypass
- Privilege escalation
- Account impersonation
- Object-property manipulation
- Business-logic abuse
- Information disclosure
- File access
- Database modification
- Denial of service
- Server-Side Request Forgery
- Command execution
- Remote code execution
- Persistence
- Movement into internal systems
The final impact depends on the serialization format, available classes, application code, runtime behavior, privileges, and network access.
Common Types of Insecure Deserialization
Object Property Manipulation
An attacker may change properties stored inside a serialized object.
Potential targets include:
- User identifiers
- Account roles
- Authorization flags
- Product prices
- Discount percentages
- Order quantities
- Payment status
- Subscription level
- Feature permissions
- Workflow state
- Tenant identifiers
If the application trusts these values without checking them against authoritative server-side records, the attacker may bypass important business rules.
Privilege Escalation Through Deserialization
A serialized object may contain a role, permission level, or administrator flag.
Changing the value may cause the application to reconstruct an object that appears to belong to a more privileged user.
This is not always possible, particularly when serialized values are strongly authenticated and all authorization decisions are repeated on the server. However, applications should never treat a reconstructed role value as sufficient proof of authorization.
Authentication Bypass
Some systems serialize session or identity information and send it to the client.
If the serialized state can be modified, replayed, or replaced, an attacker may be able to impersonate another account or bypass part of the authentication process.
Secure session tokens should be unpredictable, integrity-protected, short-lived where appropriate, and validated against server-side security state.
Native Object Deserialization
Some platforms provide serialization systems capable of restoring complex objects with class information and references.
These mechanisms may automatically:
- Create objects
- Set properties
- Invoke constructors
- Run callbacks
- Resolve classes
- Restore references
- Trigger cleanup or conversion methods
Deserializing attacker-controlled native objects can be especially dangerous because object reconstruction may perform more than simple data parsing.
Gadget-Chain Deserialization
A gadget is existing code in the application or one of its dependencies that performs a useful operation when invoked in an unintended context.
A single gadget may not be dangerous by itself. When multiple behaviors can be connected, they may form a gadget chain that produces a harmful result during or after deserialization.
Possible effects include:
- Reading a file
- Writing a file
- Making a network request
- Starting a process
- Invoking an administrative function
- Executing code
The attacker does not necessarily upload a new malicious program. They abuse classes and methods already available in the application’s runtime.
Type Confusion
Serialized data may include type information or influence which class the application creates.
If the application expects one harmless type but reconstructs another, the substituted object may expose additional methods or dangerous behavior.
Strict control over permitted types is essential when polymorphic deserialization is used.
JSON Deserialization Vulnerabilities
JSON is often considered a simple data format, but JSON deserialization can still be unsafe.
Problems may occur when a framework:
- Accepts attacker-controlled type metadata
- Automatically creates arbitrary classes
- Binds unrestricted properties
- Invokes setters with side effects
- Performs polymorphic deserialization
- Converts fields into dangerous object types
- Trusts security-sensitive values
Using JSON does not automatically prevent insecure deserialization. The safety depends on how the parser maps data into application objects.
XML Object Deserialization
XML may be used to represent application objects rather than simple documents.
An unsafe XML object deserializer might allow attacker-controlled types, properties, references, or callbacks. This is separate from XXE, although an XML-processing pipeline could contain both vulnerabilities.
Cookie-Based Deserialization
Applications sometimes place serialized preferences, shopping-cart data, or session state inside browser cookies.
A user controls the browser and can modify cookie values. Therefore, client-side serialized objects must always be treated as untrusted, even if the application originally generated them.
Encryption alone may hide the data but does not necessarily guarantee its integrity. Authenticated encryption or a strong integrity mechanism is needed when client-side state is unavoidable.
Session Deserialization
Some frameworks store serialized session objects in files, databases, caches, or distributed session services.
An attacker who gains write access to session storage or exploits another feature that modifies session content may be able to supply a dangerous object for later deserialization.
Session stores require authentication, access control, network isolation, and integrity protection.
Message-Queue Deserialization
Distributed applications exchange serialized messages through brokers and queues.
A background worker may assume every message came from a trusted producer. If an attacker compromises a producer, obtains queue credentials, or reaches an exposed broker, the worker may deserialize malicious data with powerful service permissions.
Message authentication and authorization are necessary even inside private networks.
Cache-Based Deserialization
Applications may serialize objects before placing them in a cache.
If the cache is exposed, shared incorrectly, or writable by a less trusted service, an attacker may replace cached content with a malicious serialized value that a privileged application later reconstructs.
Second-Order Deserialization
Second-order insecure deserialization occurs when malicious serialized data is stored first and processed later.
The initial upload or API request may not trigger visible behavior. A scheduled job, reporting service, administrator action, or background worker eventually retrieves and deserializes the object.
This delay complicates detection and incident investigation.
Denial-of-Service Deserialization
A serialized object may be designed to consume excessive resources during reconstruction.
It could trigger:
- Extremely deep object graphs
- Huge collections
- Recursive references
- Expensive conversions
- Excessive memory allocation
- Repeated object creation
- Long-running calculations
Even when code execution is impossible, unsafe deserialization may make the application unavailable.
Where Do Insecure Deserialization Vulnerabilities Appear?
The vulnerability may occur wherever applications reconstruct structured objects from external or shared data.
Common locations include:
- Browser cookies
- Session tokens
- API requests
- Message queues
- Distributed caches
- File uploads
- Import and export tools
- Mobile application traffic
- Desktop applications
- Remote procedure calls
- Background jobs
- Database fields
- Workflow engines
- Plug-in systems
- Authentication platforms
- Gaming applications
- E-commerce systems
- Cloud-management tools
- Machine-learning pipelines
- Internal microservices
Data from an internal service should not automatically be considered trustworthy. If one service is compromised, insecure deserialization can help an attacker move into another.
What Causes Insecure Deserialization?
The root cause is treating untrusted serialized data as a trusted application object.
Common development mistakes include:
- Deserializing native objects from user input
- Accepting serialized data in cookies
- Allowing arbitrary object types
- Enabling unsafe polymorphic type handling
- Trusting client-supplied roles or permissions
- Using a weak or missing integrity check
- Using encryption without authentication
- Exposing session or cache storage
- Trusting internal message queues
- Running old serialization libraries
- Including unnecessary dependencies
- Deserializing before validating
- Applying authorization only to the serialized object
- Running the application with excessive privileges
- Failing to limit object size and complexity
- Logging serialized secrets
- Using dangerous legacy formats
The safest design treats serialized input as data, not executable or behavior-rich program state.
What Is the Difference Between Serialization and Encoding?
Encoding changes the representation of data so it can be stored or transmitted. It does not normally reconstruct application objects with behavior.
Examples include:
- Base64
- URL encoding
- Character encoding
- Hexadecimal representation
Serialization represents structured application data or object state.
Encoding a serialized value does not make it safe. Base64, for example, is reversible and provides no authentication, confidentiality, or integrity protection by itself.
What Is the Difference Between Deserialization and Parsing?
Parsing converts formatted input into a structured representation.
Deserialization often goes further by recreating application-specific objects, types, references, or state.
The distinction is important because a safe parser that returns strings, numbers, lists, and maps usually exposes less behavior than a native object deserializer.
However, any parser can become risky if it automatically constructs powerful objects or binds unrestricted properties.
What Is the Difference Between Insecure Deserialization and Code Injection?
Code injection directly places attacker-controlled instructions into an interpreter or runtime.
Insecure deserialization reconstructs an object whose type, state, or automatic behavior causes an unintended action.
Both may lead to remote code execution, but the path to execution is different. Deserialization attacks often reuse existing code rather than directly introducing a new program.
What Is the Difference Between Insecure Deserialization and Mass Assignment?
Mass assignment occurs when a framework automatically copies user-supplied fields into an object, including fields the user should not control.
Insecure deserialization reconstructs a serialized representation that may include properties, types, references, and behavior.
The vulnerabilities overlap when a deserializer permits changes to sensitive object properties, but native object deserialization may expose much more than property assignment.
What Is the Difference Between Insecure Deserialization and Prototype Pollution?
Prototype pollution changes inherited properties in prototype-based languages, particularly JavaScript.
Insecure deserialization reconstructs an unsafe object from untrusted data.
An unsafe object merge or deserialization process may contribute to prototype pollution, but the two weaknesses are not identical.
Warning Signs of a Deserialization Attack
Developers and security teams may observe:
- Unusual serialized data in requests
- Unexpected type or class names
- Modified session or state cookies
- Invalid object signatures
- Deserialization exceptions
- Unexpected classes being instantiated
- Strange process creation
- Unusual file access
- Outbound connections from a deserialization endpoint
- Background workers performing unauthorized actions
- Sudden memory or CPU spikes
- Deeply nested object structures
- Application crashes during object reconstruction
- Unexpected administrator flags or roles
- Replayed serialized messages
- Unknown data appearing in queues or caches
- Server errors involving object conversion
- Security-sensitive fields changing without corresponding business events
Application teams should distinguish normal data-format errors from patterns indicating deliberate manipulation.
How Can Developers Prevent Insecure Deserialization?
Avoid Native Object Deserialization of Untrusted Data
The strongest defense is to avoid deserializing untrusted data into native, behavior-rich application objects.
Use a simple data format and parse it into limited structures such as:
- Strings
- Numbers
- Booleans
- Lists
- Maps
- Explicit data-transfer objects
The application should then copy validated values into internal domain objects.
Use Explicit Data Schemas
Define the expected fields, types, lengths, ranges, and structure.
Reject:
- Unknown properties
- Unexpected types
- Excessive nesting
- Oversized arrays
- Missing required fields
- Duplicate security-sensitive fields
- Values outside permitted ranges
Schema validation reduces ambiguity and prevents the client from supplying internal object state the API does not require.
Allowlist Permitted Types
If object deserialization cannot be avoided, allow only a small, explicit set of safe types.
Do not allow the serialized input to specify an arbitrary class.
The allowlist must be enforced by the deserialization mechanism before the object is created, not checked only after reconstruction.
Disable Polymorphic Type Handling
Many serialization frameworks support polymorphism, allowing input to determine which subtype should be created.
Disable this feature when it is unnecessary.
When polymorphism is required, use a fixed server-side mapping between simple type identifiers and approved classes. Never treat a client-supplied class name as authoritative.
Use Safe Serialization Formats
Prefer formats designed for data exchange rather than native object reconstruction.
The format should not automatically:
- Instantiate arbitrary classes
- Invoke application methods
- Execute callbacks
- Resolve remote resources
- Load code
- Access the filesystem
A simpler format reduces risk, but secure parser settings and validation remain necessary.
Authenticate Serialized Data
If serialized state must be stored on the client or pass through an untrusted channel, protect its integrity with a strong cryptographic mechanism.
Use:
- Authenticated encryption
- A keyed message authentication code
- Secure, maintained token standards
- Proper key management
Verify authenticity before deserializing or acting on the data.
A plain checksum or unkeyed hash does not prevent an attacker from modifying the data and calculating a new value.
Do Not Store Authorization Decisions in Client Data
Do not trust client-supplied values for:
- User roles
- Administrative status
- Account ownership
- Product prices
- Payment completion
- Subscription level
- Tenant membership
- Approval status
Retrieve security-sensitive information from an authoritative server-side source and repeat authorization checks for every protected action.
Validate Before Constructing Domain Objects
Parse incoming data into a limited intermediate representation.
Validate the complete structure before creating internal objects or invoking business logic.
This separation reduces the chance that object construction triggers dangerous behavior before validation occurs.
Use Minimal Data-Transfer Objects
Create dedicated input models containing only fields required for the specific operation.
Do not deserialize API requests directly into large internal objects that also contain:
- Roles
- Ownership fields
- Internal identifiers
- Security flags
- Workflow state
- Database configuration
- Administrative properties
Smaller input models create a clearer security boundary.
Apply Resource Limits
Place limits on:
- Input size
- Object depth
- Collection length
- String length
- Number of objects
- Processing time
- Memory use
- Reference count
These controls help prevent denial-of-service attacks.
Restrict Deserialization Permissions
Run code that processes untrusted data with minimal:
- Filesystem access
- Network connectivity
- Cloud permissions
- Database privileges
- Process-execution rights
- Access to secrets
OWASP recommends isolating or restricting deserialization processes so malicious objects cannot freely reach system resources. OWASP’s Deserialization Cheat Sheet discusses defense strategies for several common runtimes.
Isolate High-Risk Processing
Applications that must process legacy serialized formats can place the operation inside:
- A sandbox
- A restricted container
- A dedicated low-privilege service
- A temporary environment
- A network-isolated worker
The process should receive only the minimum data and resources required.
Restrict Outbound Network Access
A malicious object may attempt to connect to an external or internal destination.
Limit application-server egress through:
- Firewalls
- Proxies
- Network policies
- Security groups
- Service meshes
A service that does not require general internet access should not have it.
Keep Dependencies Updated
Deserialization gadget chains frequently depend on behaviors inside third-party libraries.
Maintain an inventory of:
- Serialization frameworks
- Application libraries
- Plug-ins
- Transitive dependencies
- Runtime components
Remove unused libraries because every available class may increase the potential attack surface.
Replace Unsafe Legacy Formats
Migrate from native or language-specific object serialization to explicitly defined data formats.
A safe migration should consider:
- Backward compatibility
- Existing stored sessions
- Message queues
- Database records
- Rolling deployments
- Key rotation
- Replay protection
Do not leave the legacy deserializer enabled indefinitely as a silent fallback.
Use Versioned Messages
Define a message or schema version controlled by the application.
Reject unknown versions instead of guessing how to interpret them. This prevents older, less secure object structures from reappearing unexpectedly.
Add Replay Protection
Signed data may still be replayed if the application accepts the same valid object repeatedly.
For sensitive operations, include and verify:
- Expiration time
- Unique message identifier
- Intended audience
- Issuer
- Transaction context
- One-time state where appropriate
The integrity of a message does not prove it is fresh or appropriate for the current action.
Why Is a Digital Signature Not a Complete Defense?
A strong signature or MAC can prove that serialized data was created by a trusted party and has not been modified.
However, it does not make unsafe deserialization harmless.
A legitimate serialized object may still become dangerous if:
- A signing key is compromised
- Another trusted service can sign attacker-controlled data
- Old signed objects can be replayed
- The application signs data before validating it
- The deserializer contains a vulnerability
- A trusted internal source is compromised
- The same key is used across unrelated contexts
Integrity protection is valuable, but the application should still use safe formats, explicit schemas, type restrictions, least privilege, and authorization.
Can a Web Application Firewall Prevent Insecure Deserialization?
A web application firewall, or WAF, may detect known serialized signatures, suspicious class names, oversized structures, or common attack patterns.
It cannot reliably understand every:
- Serialization format
- Application class
- Dependency
- Object graph
- Cryptographic wrapper
- Binary message
- Business rule
- Background queue
A WAF can provide additional monitoring or temporary containment, but the unsafe deserialization mechanism must be removed or secured.
How Should Insecure Deserialization Be Tested?
Testing must be performed only with explicit authorization.
A security review should identify:
- Every deserialization function
- Serialized cookies and tokens
- API endpoints accepting objects
- Message-queue consumers
- Cache readers
- Session storage
- Uploaded object files
- Database fields containing serialized state
- Remote procedure call interfaces
- Background workers
- Legacy integration formats
Reviewers should determine:
- Whether input can specify object types
- Which classes are permitted
- Whether object callbacks are triggered
- Whether data integrity is verified
- Whether signatures are checked before parsing
- Which security-sensitive fields are accepted
- Whether authorization is repeated
- What permissions the process has
- Whether input size and depth are limited
- Whether unsafe libraries are present
- Whether replay is possible
Testing should use controlled, harmless data. It should not execute commands, disrupt services, or access unauthorized information.
How Can Organizations Detect Deserialization Attacks?
Useful monitoring sources include:
- Application logs
- Deserialization exceptions
- Process-creation records
- Endpoint detection
- File-access logs
- DNS and proxy logs
- API gateway events
- Queue and broker logs
- Cache audit records
- Authentication activity
- Cloud audit events
- CPU and memory metrics
High-value alerts include:
- A web application unexpectedly starting a process
- Unknown classes reconstructed from user input
- Repeated signature failures
- Unusual outbound traffic following object parsing
- Administrative properties changing through a client request
- A background worker receiving messages from an unknown producer
- Sudden resource exhaustion during deserialization
What Should an Organization Do After Detecting Insecure Deserialization?
Disable the Vulnerable Processing Path
Temporarily disable or restrict the affected endpoint, queue consumer, session format, import feature, or background worker.
Block known malicious serialized input while a complete fix is prepared.
Preserve Evidence
Collect:
- Serialized request data
- Authentication records
- Application logs
- Process activity
- File changes
- Outbound network connections
- Queue messages
- Cache activity
- Cloud audit events
- Memory evidence when appropriate
Do not deserialize suspicious objects during the investigation using the same unsafe application tools.
Determine What Happened
Investigators should identify:
- Which objects were reconstructed
- Which classes were instantiated
- What methods or callbacks ran
- Whether commands executed
- Which files were accessed
- Whether credentials were exposed
- Which systems were contacted
- Whether privileges changed
- Whether data was altered
- Whether persistence was established
Rotate Exposed Secrets
If the vulnerable process could access credentials, rotate potentially exposed:
- Database passwords
- API tokens
- Cloud credentials
- Signing keys
- Session secrets
- Service-account credentials
- Deployment keys
- Administrative passwords
If an integrity key was compromised, invalidate objects signed with the old key where practical.
Revoke Sessions and Serialized Tokens
If serialized session or authentication objects were affected:
- Revoke active sessions
- Invalidate vulnerable token formats
- Rotate signing keys
- Require reauthentication
- Review privileged account activity
- Block replayed identifiers
Rebuild Compromised Systems When Necessary
If deserialization produced operating-system command or code execution, the integrity of the affected workload may no longer be trusted.
Rebuild it from a known-good image and restore necessary data from clean backups.
Replace the Unsafe Mechanism
Migrate to a limited data format with:
- Explicit schemas
- Fixed types
- Minimal input models
- Integrity protection
- Authorization checks
- Size limits
- Replay protection
- Least privilege
Review every producer and consumer of the old serialized format.
Monitor After Recovery
Continue monitoring for:
- Reuse of exposed credentials
- Replay of old serialized data
- Requests using the retired format
- Unexpected processes
- New persistence
- Modified accounts
- Suspicious queue messages
- Movement into connected systems
Can Insecure Deserialization Lead to Remote Code Execution?
Yes, in severe cases.
Remote code execution may occur when the deserializer can reconstruct attacker-selected classes and the application contains a usable chain of methods or callbacks.
However, not every insecure deserialization flaw provides code execution. Some allow only data manipulation, authorization bypass, or denial of service.
A vulnerability should still be treated seriously because the available impact can change when new dependencies or classes are added.
Is JSON Deserialization Always Safe?
No.
JSON is generally safer when it is parsed into simple values and validated against an explicit schema.
It becomes more dangerous when a framework:
- Accepts class or type metadata
- Creates arbitrary application objects
- Enables unsafe polymorphism
- Binds sensitive fields automatically
- Invokes setters with side effects
- Trusts client-supplied authorization state
The format alone does not determine security.
Does Encryption Prevent Insecure Deserialization?
Not by itself.
Encryption protects confidentiality, but encryption without authentication may not prove that data has not been modified.
Even authenticated encryption does not make a dangerous native object safe to deserialize. It only establishes that the encrypted value came from someone with the key.
Safe formats, validation, restricted types, authorization, and least privilege are still required.
Can Insecure Deserialization Affect Cloud Applications?
Yes.
A compromised cloud application may use deserialization to access:
- Workload identity credentials
- Cloud storage
- Secrets managers
- Internal APIs
- Databases
- Container platforms
- Deployment services
- Message brokers
Cloud workloads should have least-privilege identities and restricted outbound connectivity so a vulnerable deserializer cannot freely reach the wider environment.
Is Insecure Deserialization Only a Web Vulnerability?
No.
It can affect any software that reconstructs objects from untrusted or shared data, including:
- Desktop software
- Mobile applications
- Gaming platforms
- Enterprise middleware
- Build systems
- Message consumers
- Developer tools
- Cloud services
- Internet of Things devices
- Machine-learning systems
The vulnerability is defined by the trust boundary around the data, not by whether a browser is involved.
Suggested SEO title: What Is Insecure Deserialization? Risks, Signs and Prevention
Meta description: Learn how insecure deserialization lets attackers manipulate objects, bypass authorization, disrupt services, or execute code—and how schemas, safe formats, type restrictions, and integrity checks prevent it.
