PHP Serialization - Format and Entry Points for Deserializing Objects
PHP converts objects into text strings via serialize()and restores back through unserialize()The format is human-readable—each element is marked with a type letter and value length: For more information, see our review of creating CTF tasks .
O:ДЛИНА:"ИмяКласса":КОЛИЧЕСТВО_СВОЙСТВ:{свойства}- object
s:ДЛИНА:"значение"— a string with an explicit indication of the number of characters
i:число— an integer, d:число — float
b:0 or b:1 — boolean (false/true)
a:КОЛИЧЕСТВО:{элементы}— associative array
Specific example: string O:4:"User":2:{s:8:"username";s:6:"carlos";s:7:"isAdmin";b:0;}describes an object of a class Userwith two properties. Length in s:6:"carlos"must exactly match the actual number of characters - an error of one byte, and unserialize()will return false, the payload won't work silently. This is the most common reason for a "broken" exploit at CTFs. Every other participant forgets to recalculate the string length after editing a value. Every. Second.
Serialized data is found in cookies (usually base64-encoded), POST parameters, hidden form fields, session storage, and cache. OWASP classification: A08:2021 (Software and Data Integrity Failures) . CWE-502 (Deserialization of Untrusted Data) identifies the root cause: a product deserializes untrusted data without validating the result. Platforms from the MITRE CWE catalog affected by CWE-502 include Java, Ruby, PHP, Python, and JavaScript.
In the MITRE ATT&CK matrix, deserialization exploitation is mapped to T1190 (Exploit Public-Facing Application , Initial Access tactic): a crafted payload hits a public endpoint and executes code on the server without credentials. Outside of CTF, this is an initial access vector followed by tool loading (T1105, Ingress Tool Transfer) and lateral movement across the infrastructure. Through controlled entry into unserialize()The attacker obtains RCE without credentials. No SQL injection or file upload is required. A PHP unserialize vulnerability occurs when user data enters a function without filtering. PHP will restore an object of any class available in the execution context—not the one the application expects. Hence the alternative name, object injection.
PHP Magic Methods - Exploiting __wakeup and __destruct
Deserialization of PHP objects becomes an attack vector thanks to magic methods—functions that PHP automatically calls at certain stages of an object's lifecycle. Three key methods for exploiting PHP magic methods are:
__wakeup()fires immediately after deserialization. If inside - eval(), system() or file_put_contents()With parameters from the object's properties, the attacker controls the arguments by substituting values in the serialized string. Payload generation is simple: create a class instance with the desired property value, serialize it via serialize(), you send.
__destruct()is called when an object is destroyed—even if the application doesn't access the deserialized object at all. The script will terminate, the garbage collector will call the destructor, and the code will execute. The attack is completed before the application can decide whether it needs the object or not. The destructor doesn't care.
__toString()triggered when casting an object to a string: echo, concatenation, logging. The deserialized object was hit by a string operation—the method will be executed.
The classic CTF pattern is a class with a destructor that writes data to a file. Object Loggerwith properties $logFile = "shell.php" And $logData = "<?php system($_GET['c']);?>"is created silently during deserialization, and when the script is completed __destruct()causes file_put_contents()— the web shell ends up on disk. Generating the payload via PHP CLI requires just this one-liner:
php -r "class Logger{public \$logFile='shell.php';public \$logData='<?php system(\$_GET[\"c\"]);?>';} echo serialize(new Logger);"
Bypass is a regular occurrence in CTFs. __wakeup()for PHP versions prior to 7.4 (CVE-2016-7124). The trick is simple: specify a larger number of properties in the serialized string than the actual number. O:4:"Test":2:{s:3:"cmd";s:2:"id";}instead of O:4:"Test":1:{...}PHP will skip the call. __wakeup(), But __destruct()will work normally. Useful when __wakeup()contains a check that blocks exploitation - resets properties or causes die()This method works up to PHP 8.0, which is usually explicitly stated in the problem statement.
Type juggling – PHP unserialize vulnerability through type substitution
A vector that Russian-language sources barely disclose. According to research by PortSwigger Web Security Academy, PHP with the weak comparison operator ( ==) opens a separate exploitation path - not RCE, but authentication bypass.
PHP when comparing ==converts types automatically. In PHP 7.x, the expression 0 == "Example string"will return true, because a string without leading digits is converted to an integer 0. Expression 5 == "5 of something"will return too true— PHP starts the string with a number and discards the remainder. This behavior becomes a vulnerability during deserialization:
$login = unserialize($_COOKIE);
if ($login['password'] == $password) {
// доступ разрешён
}
If an attacker replaces the value through deserialization passwordto integer 0instead of the expected string, the condition 0 == "s3cur3p@ss"will return trueDeserialization preserves the type: an integer remains an integer, and is not converted to a string, as when received from a GET/POST parameter. Payload to bypass — a:1:{s:8:"password";i:0;}. One letter iinstead of s, zero instead of the password hash. That's it.
In PHP 8.0+ comparison 0 == "Example string"returns false. But 5 == "5 of something"still gives trueFor CTF tasks with type juggling, PHP 7.x is explicitly specified in the condition or in the header. X-Powered-By. See a loose comparison and unserialize()In one script, check for type substitution before you start building a gadget chain.
Gadget chain PHP — POP chain and phpggc in practice
One class with eval()In the magic method, this is a textbook example. In real-world CTF tasks at medium-hard levels, you need to build a chain of calls through several classes—a Property-Oriented Programming (POP) chain. It's the PHP gadget chain that makes deserialization a truly dangerous vector.
POP chain principle: __destruct()the first object calls a method on a property, which itself is an object of another class. That one, through __toString(), __call()or the usual method pulls the third one - and so on up to the sink function ( eval(), system(), file_put_contents()). The attacker doesn't inject new code, but reuses existing application or framework methods, combining them into a sequence the developers didn't intend. It's quite beautiful, if you think about it.
phpggc usage for well-known frameworks
To automate POP chain searches, frameworks include phpggc, a library of ready-made gadget chains. View all available chains: phpggc -lFiltering by framework: phpggc -l Laravel. Payload generation: phpggc Laravel/RCE1 system idcreates a serialized string that executes system('id')when deserializing in a Laravel application.
Typical CTF workflow: define the framework via response headers or composer.json(via LFI or source disclosure), find a chain in phpggc, generate a payload, encode it in base64, and insert it into a cookie. Sounds simple. But phpggc only knows public chains—for custom applications, you'll have to build the chain manually.
CVE-2020-15148 – Manual Gadget Chain Construction in Yii2
A manual construction can be seen in CVE-2020-15148, a vulnerability in Yii Framework 2 before version 2.0.38 (CVSS 8.9 HIGH, vector CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:C/C:L/I:H/A:H, CWE-502). According to EPSS, it's 0.7754, Top 1% in terms of exploitability. The Nuclei detection template is http/cves/2020/CVE-2020-15148.yaml.
Researchers from RedTeam Pentesting described the chain tracing process: the search begins with grepby __destructin the framework's source code. In Yii 2.0.37, the only result is a class yii\db\BatchQueryResultwith a destructor calling $this->reset()Method reset()causes $this->_dataReader->close()Substituting in _dataReaderobject yii\web\DbSession, we receive a call composeFields(), which uses call_user_func($this->writeCallback, $this)The final step is to direct writeCallbackon the method generateDependencyData()class yii\caching\ExpressionDependency, containing eval("return {$this->expression};").
Final chain: BatchQueryResult.__destruct() → reset() → DbSession.close() → composeFields() → call_user_func() → ExpressionDependency.generateDependencyData() → eval(). Five classes, none of which contain a direct call system()— but together they yield RCE. The vulnerability was fixed in version 2.0.38 of the package. yiisoft/yii2.
A contrasting example is CVE-2023-30534 in Cacti v1.2.24 (CVSS 4.3 MEDIUM, CWE-502). Two instances of insecure deserialization exist, and the gadget chain is present in the vendor directory via phpseclib, but the necessary gadgets are not enabled, making exploitation impossible. CISA rated it Track* (PoC present, automation absent, technical impact partial). Deserialization without accessible gadgets is a vulnerability, but not an exploitable one. The gadget chain is a key condition for pop-chain exploitation in PHP. Without it, the vulnerability is simply an entry in the CVE database.
PHAR deserialization without calling unserialize()
PHAR (PHP Archive) stores metadata in serialized form. When accessing a file through a stream wrapper phar://PHP automatically deserializes metadata - without explicit call unserialize()in the code. The attack surface extends to all functions supported by stream wrappers: file_exists(), is_dir(), file_get_contents(), fopen(), filesize().
Technique: Create a PHAR archive with a malicious object in the metadata, containing a gadget chain. To bypass format checks during upload, a polyglot is used—a file that is valid both as a JPEG and a PHAR. Header \xFF\xD8(JPEG magic bytes) is placed first to keep the image loader happy and the marker __HALT_COMPILER();points PHP to the start of the PHAR data. You upload the polyglot as an "avatar" via the standard upload command, then access it via the path phar://uploads/avatar.jpgIn a function with wrappers support, metadata deserialization is triggered, and the gadget chain is executed. The avatar becomes a backdoor.
On CTFs, these tasks are considered hard. Two conditions are needed simultaneously: control over the path in a function with stream wrapper support, plus the ability to upload a file to the server. This is less common than a direct solution. unserialize(), but it is the PHAR vector that breaks the assumption “we don’t use unserialize, so we’re safe.”
PHP converts objects into text strings via serialize()and restores back through unserialize()The format is human-readable—each element is marked with a type letter and value length: For more information, see our review of creating CTF tasks .
O:ДЛИНА:"ИмяКласса":КОЛИЧЕСТВО_СВОЙСТВ:{свойства}- object
s:ДЛИНА:"значение"— a string with an explicit indication of the number of characters
i:число— an integer, d:число — float
b:0 or b:1 — boolean (false/true)
a:КОЛИЧЕСТВО:{элементы}— associative array
Specific example: string O:4:"User":2:{s:8:"username";s:6:"carlos";s:7:"isAdmin";b:0;}describes an object of a class Userwith two properties. Length in s:6:"carlos"must exactly match the actual number of characters - an error of one byte, and unserialize()will return false, the payload won't work silently. This is the most common reason for a "broken" exploit at CTFs. Every other participant forgets to recalculate the string length after editing a value. Every. Second.
Serialized data is found in cookies (usually base64-encoded), POST parameters, hidden form fields, session storage, and cache. OWASP classification: A08:2021 (Software and Data Integrity Failures) . CWE-502 (Deserialization of Untrusted Data) identifies the root cause: a product deserializes untrusted data without validating the result. Platforms from the MITRE CWE catalog affected by CWE-502 include Java, Ruby, PHP, Python, and JavaScript.
In the MITRE ATT&CK matrix, deserialization exploitation is mapped to T1190 (Exploit Public-Facing Application , Initial Access tactic): a crafted payload hits a public endpoint and executes code on the server without credentials. Outside of CTF, this is an initial access vector followed by tool loading (T1105, Ingress Tool Transfer) and lateral movement across the infrastructure. Through controlled entry into unserialize()The attacker obtains RCE without credentials. No SQL injection or file upload is required. A PHP unserialize vulnerability occurs when user data enters a function without filtering. PHP will restore an object of any class available in the execution context—not the one the application expects. Hence the alternative name, object injection.
PHP Magic Methods - Exploiting __wakeup and __destruct
Deserialization of PHP objects becomes an attack vector thanks to magic methods—functions that PHP automatically calls at certain stages of an object's lifecycle. Three key methods for exploiting PHP magic methods are:
__wakeup()fires immediately after deserialization. If inside - eval(), system() or file_put_contents()With parameters from the object's properties, the attacker controls the arguments by substituting values in the serialized string. Payload generation is simple: create a class instance with the desired property value, serialize it via serialize(), you send.
__destruct()is called when an object is destroyed—even if the application doesn't access the deserialized object at all. The script will terminate, the garbage collector will call the destructor, and the code will execute. The attack is completed before the application can decide whether it needs the object or not. The destructor doesn't care.
__toString()triggered when casting an object to a string: echo, concatenation, logging. The deserialized object was hit by a string operation—the method will be executed.
The classic CTF pattern is a class with a destructor that writes data to a file. Object Loggerwith properties $logFile = "shell.php" And $logData = "<?php system($_GET['c']);?>"is created silently during deserialization, and when the script is completed __destruct()causes file_put_contents()— the web shell ends up on disk. Generating the payload via PHP CLI requires just this one-liner:
php -r "class Logger{public \$logFile='shell.php';public \$logData='<?php system(\$_GET[\"c\"]);?>';} echo serialize(new Logger);"
Bypass is a regular occurrence in CTFs. __wakeup()for PHP versions prior to 7.4 (CVE-2016-7124). The trick is simple: specify a larger number of properties in the serialized string than the actual number. O:4:"Test":2:{s:3:"cmd";s:2:"id";}instead of O:4:"Test":1:{...}PHP will skip the call. __wakeup(), But __destruct()will work normally. Useful when __wakeup()contains a check that blocks exploitation - resets properties or causes die()This method works up to PHP 8.0, which is usually explicitly stated in the problem statement.
Type juggling – PHP unserialize vulnerability through type substitution
A vector that Russian-language sources barely disclose. According to research by PortSwigger Web Security Academy, PHP with the weak comparison operator ( ==) opens a separate exploitation path - not RCE, but authentication bypass.
PHP when comparing ==converts types automatically. In PHP 7.x, the expression 0 == "Example string"will return true, because a string without leading digits is converted to an integer 0. Expression 5 == "5 of something"will return too true— PHP starts the string with a number and discards the remainder. This behavior becomes a vulnerability during deserialization:
$login = unserialize($_COOKIE);
if ($login['password'] == $password) {
// доступ разрешён
}
If an attacker replaces the value through deserialization passwordto integer 0instead of the expected string, the condition 0 == "s3cur3p@ss"will return trueDeserialization preserves the type: an integer remains an integer, and is not converted to a string, as when received from a GET/POST parameter. Payload to bypass — a:1:{s:8:"password";i:0;}. One letter iinstead of s, zero instead of the password hash. That's it.
In PHP 8.0+ comparison 0 == "Example string"returns false. But 5 == "5 of something"still gives trueFor CTF tasks with type juggling, PHP 7.x is explicitly specified in the condition or in the header. X-Powered-By. See a loose comparison and unserialize()In one script, check for type substitution before you start building a gadget chain.
Gadget chain PHP — POP chain and phpggc in practice
One class with eval()In the magic method, this is a textbook example. In real-world CTF tasks at medium-hard levels, you need to build a chain of calls through several classes—a Property-Oriented Programming (POP) chain. It's the PHP gadget chain that makes deserialization a truly dangerous vector.
POP chain principle: __destruct()the first object calls a method on a property, which itself is an object of another class. That one, through __toString(), __call()or the usual method pulls the third one - and so on up to the sink function ( eval(), system(), file_put_contents()). The attacker doesn't inject new code, but reuses existing application or framework methods, combining them into a sequence the developers didn't intend. It's quite beautiful, if you think about it.
phpggc usage for well-known frameworks
To automate POP chain searches, frameworks include phpggc, a library of ready-made gadget chains. View all available chains: phpggc -lFiltering by framework: phpggc -l Laravel. Payload generation: phpggc Laravel/RCE1 system idcreates a serialized string that executes system('id')when deserializing in a Laravel application.
Typical CTF workflow: define the framework via response headers or composer.json(via LFI or source disclosure), find a chain in phpggc, generate a payload, encode it in base64, and insert it into a cookie. Sounds simple. But phpggc only knows public chains—for custom applications, you'll have to build the chain manually.
CVE-2020-15148 – Manual Gadget Chain Construction in Yii2
A manual construction can be seen in CVE-2020-15148, a vulnerability in Yii Framework 2 before version 2.0.38 (CVSS 8.9 HIGH, vector CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:C/C:L/I:H/A:H, CWE-502). According to EPSS, it's 0.7754, Top 1% in terms of exploitability. The Nuclei detection template is http/cves/2020/CVE-2020-15148.yaml.
Researchers from RedTeam Pentesting described the chain tracing process: the search begins with grepby __destructin the framework's source code. In Yii 2.0.37, the only result is a class yii\db\BatchQueryResultwith a destructor calling $this->reset()Method reset()causes $this->_dataReader->close()Substituting in _dataReaderobject yii\web\DbSession, we receive a call composeFields(), which uses call_user_func($this->writeCallback, $this)The final step is to direct writeCallbackon the method generateDependencyData()class yii\caching\ExpressionDependency, containing eval("return {$this->expression};").
Final chain: BatchQueryResult.__destruct() → reset() → DbSession.close() → composeFields() → call_user_func() → ExpressionDependency.generateDependencyData() → eval(). Five classes, none of which contain a direct call system()— but together they yield RCE. The vulnerability was fixed in version 2.0.38 of the package. yiisoft/yii2.
A contrasting example is CVE-2023-30534 in Cacti v1.2.24 (CVSS 4.3 MEDIUM, CWE-502). Two instances of insecure deserialization exist, and the gadget chain is present in the vendor directory via phpseclib, but the necessary gadgets are not enabled, making exploitation impossible. CISA rated it Track* (PoC present, automation absent, technical impact partial). Deserialization without accessible gadgets is a vulnerability, but not an exploitable one. The gadget chain is a key condition for pop-chain exploitation in PHP. Without it, the vulnerability is simply an entry in the CVE database.
PHAR deserialization without calling unserialize()
PHAR (PHP Archive) stores metadata in serialized form. When accessing a file through a stream wrapper phar://PHP automatically deserializes metadata - without explicit call unserialize()in the code. The attack surface extends to all functions supported by stream wrappers: file_exists(), is_dir(), file_get_contents(), fopen(), filesize().
Technique: Create a PHAR archive with a malicious object in the metadata, containing a gadget chain. To bypass format checks during upload, a polyglot is used—a file that is valid both as a JPEG and a PHAR. Header \xFF\xD8(JPEG magic bytes) is placed first to keep the image loader happy and the marker __HALT_COMPILER();points PHP to the start of the PHAR data. You upload the polyglot as an "avatar" via the standard upload command, then access it via the path phar://uploads/avatar.jpgIn a function with wrappers support, metadata deserialization is triggered, and the gadget chain is executed. The avatar becomes a backdoor.
On CTFs, these tasks are considered hard. Two conditions are needed simultaneously: control over the path in a function with stream wrapper support, plus the ability to upload a file to the server. This is less common than a direct solution. unserialize(), but it is the PHAR vector that breaks the assumption “we don’t use unserialize, so we’re safe.”