Insecure Deserialization Explained

Share

TL;DR

Insecure deserialization occurs when applications deserialize untrusted data that can be manipulated to execute code or manipulate logic. This is primarily a concern in languages like Java, PHP, and Python that have native object serialization. Most JavaScript/TypeScript apps using JSON are not vulnerable to classic deserialization attacks, but you should still validate data structure and types.

What Is Insecure Deserialization?

Serialization converts objects to a format that can be stored or transmitted. Deserialization converts that data back into objects. When applications deserialize data from untrusted sources, attackers can manipulate that data to:

  • Execute arbitrary code
  • Manipulate application logic
  • Bypass authentication
  • Access sensitive data

Is My JavaScript App at Risk?

Good news: JavaScript's JSON.parse() doesn't execute code during parsing. Most modern JavaScript apps that use JSON for data exchange aren't vulnerable to classic deserialization attacks.

However, you might be at risk if you:

  • Use eval() or new Function() with user data
  • Use libraries with custom object serialization
  • Trust serialized objects in cookies or tokens without validation
  • Have a Node.js backend using libraries like node-serialize

JavaScript-Specific Risks

Dangerous: Using eval() with User Data

Never do this
// EXTREMELY DANGEROUS
const userData = req.body.data;
const result = eval(userData);  // Remote code execution!

// Also dangerous
const fn = new Function('return ' + userData);
fn();

Safer: JSON with Validation

Safe approach with validation
import { z } from 'zod';

const UserSchema = z.object({
  id: z.string().uuid(),
  name: z.string().max(100),
  email: z.string().email(),
  role: z.enum(['user', 'admin'])
});

// Parse and validate in one step
const user = UserSchema.parse(JSON.parse(requestBody));
// If validation fails, it throws an error

Where It Matters More

Insecure deserialization is more critical in:

  • Java applications: Java's ObjectInputStream can execute code during deserialization
  • PHP applications: PHP's unserialize() has led to many RCE vulnerabilities
  • Python applications: pickle module can execute arbitrary code

Is JSON.parse() safe?

JSON.parse() is safe from code execution. It only creates data structures (objects, arrays, strings, numbers, booleans, null). It doesn't execute functions or create class instances.

What about JWT tokens?

JWT parsing itself is safe, but you must validate the signature. Never trust the payload of a JWT without verifying its signature with your secret key.

Should I still validate JSON data?

Yes! While JSON.parse() won't execute code, you should validate the structure and types of parsed data. This prevents logic bugs and ensures data integrity.

Scan for Security Issues

Our scanner checks for dangerous patterns in your code.

Start Free Scan
Vulnerability Guides

Insecure Deserialization Explained