Course contentsShow
← Security
Lesson 1187 of 3,05224. Application Security - Input ValidationFree lesson

PHP Object Injection and Unserialize Attacks

Exploiting PHP unserialize(), magic methods, POP chains, and constructing object injection exploits.

PHP Object Injection and Unserialize Attacks

You'll learn how attackers exploit PHP's unserialize() function to inject malicious objects and trigger dangerous "magic methods."

What Is PHP Object Injection?

PHP's unserialize() function converts serialized strings back into objects. When an application deserializes untrusted user input, attackers can craft malicious serialized objects that trigger unintended code execution through magic methods—special methods like __wakeup(), __destruct(), and __toString() that PHP automatically invokes during object lifecycle events.

Think of it like a self-assembling puzzle: when you open the box (deserialize), the pieces arrange themselves automatically—but a malicious puzzle might explode instead of forming a picture.

Core Attack Mechanics

Magic Methods: PHP automatically calls these during deserialization:

  • __wakeup() runs immediately after unserialization
  • __destruct() runs when the object is destroyed
  • __toString() runs when the object is treated as a string

POP Chains (Property-Oriented Programming): Attackers chain together existing classes in your application, setting object properties to trigger a sequence of magic method calls that ultimately execute dangerous operations—file deletion, remote code execution, SQL injection, etc.

Example Scenario

A logging class might have __destruct() that writes to a file. An attacker serializes an object with a manipulated filename property (/etc/passwd) and payload. When the application deserializes it and the object is destroyed, the malicious write occurs.

Defense Strategy

Never deserialize untrusted data. Use JSON or other data-only formats. If you must deserialize, implement strict type checking, use allowed_classes parameter (PHP 7+), and apply input validation before deserialization—though allowlisting is the only truly safe approach.

Key Takeaway: PHP object injection exploits unserialize() by crafting malicious objects whose magic methods trigger automatically, executing attacker-controlled code through POP chains; never deserialize untrusted input.