SlideShare ist ein Scribd-Unternehmen logo
1 von 40
Downloaden Sie, um offline zu lesen
Lesser Known Security Problems in
PHP Applications
Stefan Esser


                        Zend Conference
                           September 2008
                            Santa Clara, CA
The Speaker




Stefan Esser
• 8 years of PHP Core Experience
• 10 years of Security Experience
• Suhosin and The Month of PHP Bugs
• Founder and Head of R&D at SektionEins GmbH



           Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  2
Topics




• Lesser Known Security Problems
• Less Obvious Exploitation Paths
• Inter Application Exploitation
• Vulnerability Classes Discovered during Real Audits




            Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  3
The Mantra...




• Filter Input, Escape Output
  • often misunderstood
  • vulnerabilities hidden in input filters
  • wrong escaping / encoding functions
  • not every vulnerability is caused by tainted data




             Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  4
Input Filtering - Short reminder


• Filter what you actually use and
  not what you believe is the same

  <?php
     // The TikiWiki approach to input filtering

       if (!is_numeric($_REQUEST[‘id‘])) {
           die(‘Hack attack‘);   // <-- will discuss this later
       }
       ...
       $_REQUEST = array_merge($_COOKIE, $_GET, $_POST);
       // ^----- really bad idea: GPC != CGP
  ?>




               Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  5
$_SERVER and URL Encoding


• PHP_SELF and REQUEST_URI often used
• assumed to be URL encoded, but
    • PHP_SELF is never encoded (typical XSS)
    • REQUEST_URI encoding depends on client
  <?php
     if ($_SERVER[‘REQUEST_URI‘] == ‘common.php‘) {
        die(“do not call this file directly“);
     }
     // File can still be requested by common%2ephp
  ?>




             Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  6
$_REQUEST and Cookies




• never forget $_REQUEST also contains cookie data
• cookies or cookie data might be unexpected
  • injected through XSS, HTTP Response Splitting
    or other cross domain browser bug
  • TLD wide cookies - *.co.uk / *.co.kr
  • originating from another application on same domain




             Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  7
$_REQUEST and Cookie DOS




• An injected cookie might kill the application
  <?php
     // one cookie to kill them all
     if (isset($_REQUEST[‘GLOBALS‘])) {
        die(‘GLOBALS overwrite attempt‘);
     }
  ?>




             Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  8
$_REQUEST and Delayed CSRF

• An injected cookie manipulates/overrides the control
  flow of a request performed by the user
• Traditional CSRF protections useless
  <?php
     // save only modified admin options
     foreach ($_REQUEST[‘options‘] as $key => $val) {
        if (isset($options[$key]) && $options[$key] != $val) {
           saveOption($key, $val);
        }
     }
     // Because options[includePath] could be an evil cookie
     // there is a Delayed CSRF vulnerability
     // that allows remote file inclusion
  ?>


             Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  9
auto_globals_jit - Documentation




 ; When enabled, the SERVER and ENV variables are created when they're first

 ; used (Just In Time) instead of when the script starts. If these variables

 ; are not used within a script, having this directive on will result in a

 ; performance gain. The PHP directives register_globals, register_long_arrays,

 ; and register_argc_argv must be disabled for this directive to have any affect.

                                                                                         infamous documentation in php.ini




                   Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  10
auto_globals_jit - Open Questions




• Documentation is correct ?
  - Almost definitely maybe (probably)
    - Ok, no
• What about $_REQUEST ?
• Is JIT really just-in-time of first usage ?



               Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  11
auto_globals_jit - Reality



• Documentation is wrong
  • There is no just-in-time creation on first usage
  • auto_globals are usually created before the start
    of the script if the compiler detects their usage
  • or when an extension requests their creation
• The compiler just detects direct usage
  • access by variable-variables is NOT detected



             Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  12
auto_globals_jit - Security Problem


• prepended input filtering using variable-variables FAILS
• auto_globals do not exist when the filter executes
 <?php
    $filterTargets = array(‘_REQUEST‘, ‘_SERVER‘, ‘_ENV‘, ...);
    foreach ($filterTargets as $target) {
       $$target = filterRecursive((array)$$target);
    }
 ?>


• when a PHP script accesses the auto_globals they are
  created and filled with the not filtered values


             Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  13
Session Handling - Insecure Cookie Parameters




• very very common problem
• sites use SSL to protect against session identifier sniffing
• but forgets to mark session identifier cookie as secure
• attacker injects HTTP requests to get plaintext cookie




            Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  14
Session Handling - Session Data Mixup (I)




• session data is stored in /tmp by default
• can be changed by configuration
• session data is shared by all applications that store it in
  the same location
• bad for shared hosts
• but can also lead to inter application exploits



            Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  15
Session Handling - Session Data Mixup (II)



• Example 1 - Setup:
  • customer runs two applications on his own server
  • both applications contain multi-step forms
  • both applications store data of previous steps in a session
  • application 1 merges user input into the session and
    validates/filters after all steps are processed
  • application 2 merges only validated and filtered data into the
    session



              Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  16
Session Handling - Session Data Mixup (III)




• Example 1 - Exploit:
  • enter malicious content (XSS, SQL Inj.) into application 1
  • copy session identifier of application 1 into session cookie of
    application 2
  • use application 2 which trust everything within the session
  ➡ XSS payload from session eventually exploits application 2




             Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  17
Session Handling - Session Data Mixup (IV)




• Example 2 - Setup:
  • customer runs two applications on his own server
  • both applications serve a separate group of users
  • both applications are written by the same developers
  • both applications share a similar implementation




             Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  18
Session Handling - Session Data Mixup (V)


• Example 2 - Exploit:
  • attacker is a legit user of application 1
    (maybe even a moderator / admin)
  • attacker logs himself into application 1
  • and copies his session identifier into the session cookie of
    application 2
  • because the implementation of the User object is shared,
    application 2 finds a valid User object in its session
  • attacker is now logged into application 2


             Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  19
Session Handling - Session Data Mixup (V)



• Best Practices
  • store session data in different locations
    ➡ ini_set(“session.save_path“, “/tmp/application_1/“);

    ➡ user space session handler

  • embed application marker into the session
    ➡ if ((string)$_SESSION[‘application‘] !== ‘application_1‘) die();

  • encrypt session data with application specific keys



               Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  20
Session Handling - Insecure Transactions (I)



• some PHP applications choose to override the internal
  session management with a user space session handler
  - usual implementation
    •   open    - ignored

    •   read    - SELECT * FROM tb_sessions WHERE sid=:sid

    •   write   - INSERT/UPDATE tb_sessions SET data=:data WHERE sid=:sid

    •   close   - ignore

    •   destroy - ignore




                Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  21
Session Handling - Insecure Transactions (II)




• Usual implementation ignores that reading, updating
  and storing the session data forms a transaction
• Most applications with user space session handlers are
  vulnerable to session race conditions




            Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  22
Database Handling - Status Quo




• SQL Injection widely known
• SQL Transactions less known and used
• SQL Errors are seldomly handled
• Input filters let overlong input through




            Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  23
Database Handling - MySQL‘s max_packet_size



• max_packet_size configures maximum size of a packet
• anything bigger will not be sent
• overlong input can result in queries not being sent
• allows e.g. disabling logging queries
  • referer header
  • user-agent header
  • session-identifiers, ...


             Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  24
Database Handling - Truncated Data



• database columns have a maximum width
• by default MySQL will truncate any data that doesn‘t fit
      from ‘admin                x‘

      to   ‘admin                ‘

• by default string comparision will ignore trailing spaces

➡ Security Problem because there are 2 admin users now


            Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  25
Database Handling - Best Practices




• Use database transactions for application transactions
• Handle errors, assume everything could fail
• Use MySQL‘s sql_mode STRICT_ALL_TABLES
• Catch overlong input in input filtering




            Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  26
Multi-Byte Encodings - A security problem?


• PHP uses backslash escaping in many places
     ➡ (  => , ‘ => ‘, “ => “ )
• backslash escaping is a problem for multi-byte parsers if
  the encoding allows backslashes as 2nd, 3rd, ... byte
• UTF-8 not affected, but several asian encodings like
  GBK, EUC-KR, SJIS, ...
 SELECT * FROM u WHERE login='X' OR id=1/*' AND pwd='XXXXXXXXXX'

        will be parsed as

 SELECT * FROM u WHERE login='X' OR id=1/*' AND pwd='XXXXXXXXXX'




                Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  27
Multi-Byte Encodings - Still a problem


• SQL-Injection
    • mysql_real_escape_string() not safe when SET NAMES is used
• Shell-Command Injection
    • PHP <= 5.2.6 doesn‘t escape shell commands for MB-locales
• Eval/Preg-Replace/Create_Function Injection
    • PHP doesn‘t escape correctly for zend_multibyte mode
• PHP Cache/Config Injection
    • var_export() doesn‘t escape correctly for zend_multibyte mode


             Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  28
Multi-Byte Encodings - Special Case UTF-7




• UTF-7 is a 7 bit wide encoding
• Characters used -+A-Za-z0-9
• not handled by any of PHP‘s escape functions
• browsers can be tricked to parse pages as UTF-7 when
  no charset is given
➡ XSS vulnerabilities (also common on banking sites)



            Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  29
Random Numbers



• Random Number Generators
  • srand() / rand()
    • Wrapper around libc‘s rand() - 32 bit Seed
  • mt_srand() / mt_rand()
    • Mersenne Twister - 32 bit Seed
  • uniqid(?, true) / lcg_value()
    • Combined linear congruential generator - weak 64 bit Seed



              Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  30
mt_srand() / srand() - weak seeding

• PHP seeds automatically since 4.2.0
• Disadvantages of manual seeding
  • random number generator state is easier to predict
  • seeding influences other applications
  • manual seeding usually weaker than PHP‘s seeding
  <?php
     // examples for very               bad seedings
     mt_srand(time());
     mt_srand(microtime()               * 100000);
     mt_srand(microtime()               * 1000000);
     mt_srand(microtime()               * 10000000); //<- Joomla Password Reset
  ?>


             Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  31
mt_srand() / srand() - Automatic seeding


• Automatic seeding in PHP <= 5.2.5
    • time(0) * PID * 1000000 * php_combined_lcg()
• on 32bit systems
    • lower bits of time(0) and PID can be controlled
    • due to modular arithmethic product is 0 every 2.1 years
• on 64bit systems
    • precision loss during double to int conversion
    • strength around 24 bits


             Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  32
mt_rand() / rand() - weak random numbers




• numbers depend only on 32 bit seed and running time
• not suited for cryptographic secrets
• output of PRNG might leak state
• state is process-wide => PRNG is shared resource
• attacker can get fresh seed by crashing PHP



            Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  33
mt_(s)rand / (s)rand - Shared Hosting


• CGI
  • PRNG freshly seeded for every request
  • running time not necessary for prediction
• mod_php / fastcgi
  • PRNG is shared for requests handled by same process
        • e.g. Keep-Alive
  • Sharing across VHOSTS
  • mean customer can seed PRNG to attack others


               Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  34
mt_(s)rand / (s)rand - Cross Application Attacks




• applications share the same PRNG
• leak in one application allows attacking another
• seeding in one application allows attacking another
    • phpBB2 seeds random number generator and leaks state
    • allows predicting password reset feature in Wordpress




             Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  35
mt_(s)rand / (s)rand - Best Practices




• do not seed the PRNGs
• do not use PHP‘s PRNGs for cryptographic secrets
• do not directly output random numbers
• combine output of different PRNGs
• use /dev/(u)random on unix systems



           Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  36
PHP‘s ZipArchive



• 0-day Vulnerability in PHP
• exposed by applications using ZipArchive
• discovered during an audit of customer code
• reported 85 days ago to PHP‘s security response team
• unpacking a malicious ZIP can overwrite any file
    • Exploit: just name archived files like ../../../../../www/hack.php




              Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  37
HTTP Header Response Splitting/Suppression




• Protection against HTTP Response Splitting
  • introduced with PHP 5.1.2
  • not sufficient for old Netscape Proxies
  • suppresses headers containing recognized attacks
      • allows suppressing HTTP headers
      • security problem when Content-Disposition: attachment is suppressed




             Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  38
The End ?!?




   There are more unusual, lesser known and dangerous
     vulnerabilities, but we are running out of time...




           Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  39
Thank you for listening




       QUESTIONS ???


           Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  40

Weitere ähnliche Inhalte

Was ist angesagt?

Витяг з протоколу № 7.docx
Витяг з протоколу № 7.docxВитяг з протоколу № 7.docx
Витяг з протоколу № 7.docx
ssuserae1bc41
 
вимоги до оформлення методичної розробки уроку
вимоги до оформлення методичної розробки урокувимоги до оформлення методичної розробки уроку
вимоги до оформлення методичної розробки уроку
znannademcenko
 
географічне пізнання землі
географічне пізнання землігеографічне пізнання землі
географічне пізнання землі
mpr17
 

Was ist angesagt? (20)

Compton Effect
Compton EffectCompton Effect
Compton Effect
 
Tugas sistem digital 7 segmen
Tugas sistem digital 7 segmenTugas sistem digital 7 segmen
Tugas sistem digital 7 segmen
 
Kontrol magnetik
Kontrol magnetikKontrol magnetik
Kontrol magnetik
 
Орб-19 пед сабақ форма.pptx
Орб-19 пед сабақ форма.pptxОрб-19 пед сабақ форма.pptx
Орб-19 пед сабақ форма.pptx
 
Desain proses pemesinan logam
Desain proses pemesinan logamDesain proses pemesinan logam
Desain proses pemesinan logam
 
Теорія і пратика дистанційного навчання
Теорія і пратика дистанційного навчанняТеорія і пратика дистанційного навчання
Теорія і пратика дистанційного навчання
 
Transformasi sumber (tegangan dan arus)
Transformasi sumber (tegangan dan arus)Transformasi sumber (tegangan dan arus)
Transformasi sumber (tegangan dan arus)
 
Tabel kebenaran
Tabel kebenaranTabel kebenaran
Tabel kebenaran
 
Rangkuman UAS JTPT Telkom University
Rangkuman UAS JTPT Telkom UniversityRangkuman UAS JTPT Telkom University
Rangkuman UAS JTPT Telkom University
 
дидактичні погляди Сковороди
дидактичні погляди Сковородидидактичні погляди Сковороди
дидактичні погляди Сковороди
 
Fismat Kel. 4 Matriks & Vektor
Fismat Kel. 4 Matriks & VektorFismat Kel. 4 Matriks & Vektor
Fismat Kel. 4 Matriks & Vektor
 
Витяг з протоколу № 7.docx
Витяг з протоколу № 7.docxВитяг з протоколу № 7.docx
Витяг з протоколу № 7.docx
 
Laporan praktikum
Laporan praktikumLaporan praktikum
Laporan praktikum
 
вимоги до оформлення методичної розробки уроку
вимоги до оформлення методичної розробки урокувимоги до оформлення методичної розробки уроку
вимоги до оформлення методичної розробки уроку
 
Kotak Sampah Otomatis
Kotak Sampah OtomatisKotak Sampah Otomatis
Kotak Sampah Otomatis
 
Jenis dan proses interupsi
Jenis dan proses interupsiJenis dan proses interupsi
Jenis dan proses interupsi
 
Pratikum operator
Pratikum operatorPratikum operator
Pratikum operator
 
Презентація викладача ЗОШ №6 Пашко М.Г.
Презентація викладача ЗОШ №6 Пашко М.Г.Презентація викладача ЗОШ №6 Пашко М.Г.
Презентація викладача ЗОШ №6 Пашко М.Г.
 
географічне пізнання землі
географічне пізнання землігеографічне пізнання землі
географічне пізнання землі
 
Урок 08.8 Основи самозахисту. Базові елементи самозахисту в бою
Урок 08.8 Основи самозахисту. Базові елементи самозахисту в боюУрок 08.8 Основи самозахисту. Базові елементи самозахисту в бою
Урок 08.8 Основи самозахисту. Базові елементи самозахисту в бою
 

Ähnlich wie Lesser Known Security Problems in PHP Applications

JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5
Stephan Schmidt
 
9 Ways to Hack a Web App
9 Ways to Hack a Web App9 Ways to Hack a Web App
9 Ways to Hack a Web App
elliando dias
 
[CB20] Operation I am Tom: How APT actors move laterally in corporate network...
[CB20] Operation I am Tom: How APT actors move laterally in corporate network...[CB20] Operation I am Tom: How APT actors move laterally in corporate network...
[CB20] Operation I am Tom: How APT actors move laterally in corporate network...
CODE BLUE
 
Fix me if you can - DrupalCon prague
Fix me if you can - DrupalCon pragueFix me if you can - DrupalCon prague
Fix me if you can - DrupalCon prague
hernanibf
 
Introduction into PHP5 (Jeroen van Sluijs)
Introduction into PHP5 (Jeroen van Sluijs)Introduction into PHP5 (Jeroen van Sluijs)
Introduction into PHP5 (Jeroen van Sluijs)
Stefan Koopmanschap
 

Ähnlich wie Lesser Known Security Problems in PHP Applications (20)

Server Independent Programming
Server Independent ProgrammingServer Independent Programming
Server Independent Programming
 
Api Design
Api DesignApi Design
Api Design
 
JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5
 
9 Ways to Hack a Web App
9 Ways to Hack a Web App9 Ways to Hack a Web App
9 Ways to Hack a Web App
 
[CB20] Operation I am Tom: How APT actors move laterally in corporate network...
[CB20] Operation I am Tom: How APT actors move laterally in corporate network...[CB20] Operation I am Tom: How APT actors move laterally in corporate network...
[CB20] Operation I am Tom: How APT actors move laterally in corporate network...
 
Profiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / WebgrindProfiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / Webgrind
 
Fix me if you can - DrupalCon prague
Fix me if you can - DrupalCon pragueFix me if you can - DrupalCon prague
Fix me if you can - DrupalCon prague
 
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry PiGrâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
 
Whatever it takes - Fixing SQLIA and XSS in the process
Whatever it takes - Fixing SQLIA and XSS in the processWhatever it takes - Fixing SQLIA and XSS in the process
Whatever it takes - Fixing SQLIA and XSS in the process
 
meet.php #11 - Huston, we have an airbrake
meet.php #11 - Huston, we have an airbrakemeet.php #11 - Huston, we have an airbrake
meet.php #11 - Huston, we have an airbrake
 
Building and managing applications fast for IBM i
Building and managing applications fast for IBM iBuilding and managing applications fast for IBM i
Building and managing applications fast for IBM i
 
Jun Heider - Flex Application Profiling By Example
Jun Heider - Flex Application Profiling By ExampleJun Heider - Flex Application Profiling By Example
Jun Heider - Flex Application Profiling By Example
 
Web backdoors attacks, evasion, detection
Web backdoors   attacks, evasion, detectionWeb backdoors   attacks, evasion, detection
Web backdoors attacks, evasion, detection
 
PHP Development Tools 2.0 - Success Story
PHP Development Tools 2.0 - Success StoryPHP Development Tools 2.0 - Success Story
PHP Development Tools 2.0 - Success Story
 
Basic detection tests of McAfee ENS + MVISION Insights usage for SunBurst threat
Basic detection tests of McAfee ENS + MVISION Insights usage for SunBurst threatBasic detection tests of McAfee ENS + MVISION Insights usage for SunBurst threat
Basic detection tests of McAfee ENS + MVISION Insights usage for SunBurst threat
 
Introduction into PHP5 (Jeroen van Sluijs)
Introduction into PHP5 (Jeroen van Sluijs)Introduction into PHP5 (Jeroen van Sluijs)
Introduction into PHP5 (Jeroen van Sluijs)
 
Caching and tuning fun for high scalability @ FrOSCon 2011
Caching and tuning fun for high scalability @ FrOSCon 2011Caching and tuning fun for high scalability @ FrOSCon 2011
Caching and tuning fun for high scalability @ FrOSCon 2011
 
Care and Maintenance of Your EPM Environment
Care and Maintenance of Your EPM EnvironmentCare and Maintenance of Your EPM Environment
Care and Maintenance of Your EPM Environment
 
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!
 
Caching and tuning fun for high scalability @ FOSDEM 2012
Caching and tuning fun for high scalability @ FOSDEM 2012Caching and tuning fun for high scalability @ FOSDEM 2012
Caching and tuning fun for high scalability @ FOSDEM 2012
 

Mehr von ZendCon

Mehr von ZendCon (20)

Framework Shootout
Framework ShootoutFramework Shootout
Framework Shootout
 
Zend_Tool: Practical use and Extending
Zend_Tool: Practical use and ExtendingZend_Tool: Practical use and Extending
Zend_Tool: Practical use and Extending
 
PHP on IBM i Tutorial
PHP on IBM i TutorialPHP on IBM i Tutorial
PHP on IBM i Tutorial
 
PHP on Windows - What's New
PHP on Windows - What's NewPHP on Windows - What's New
PHP on Windows - What's New
 
PHP and Platform Independance in the Cloud
PHP and Platform Independance in the CloudPHP and Platform Independance in the Cloud
PHP and Platform Independance in the Cloud
 
I18n with PHP 5.3
I18n with PHP 5.3I18n with PHP 5.3
I18n with PHP 5.3
 
Cloud Computing: The Hard Problems Never Go Away
Cloud Computing: The Hard Problems Never Go AwayCloud Computing: The Hard Problems Never Go Away
Cloud Computing: The Hard Problems Never Go Away
 
Planning for Synchronization with Browser-Local Databases
Planning for Synchronization with Browser-Local DatabasesPlanning for Synchronization with Browser-Local Databases
Planning for Synchronization with Browser-Local Databases
 
Magento - a Zend Framework Application
Magento - a Zend Framework ApplicationMagento - a Zend Framework Application
Magento - a Zend Framework Application
 
Enterprise-Class PHP Security
Enterprise-Class PHP SecurityEnterprise-Class PHP Security
Enterprise-Class PHP Security
 
PHP and IBM i - Database Alternatives
PHP and IBM i - Database AlternativesPHP and IBM i - Database Alternatives
PHP and IBM i - Database Alternatives
 
Zend Core on IBM i - Security Considerations
Zend Core on IBM i - Security ConsiderationsZend Core on IBM i - Security Considerations
Zend Core on IBM i - Security Considerations
 
Application Diagnosis with Zend Server Tracing
Application Diagnosis with Zend Server TracingApplication Diagnosis with Zend Server Tracing
Application Diagnosis with Zend Server Tracing
 
Insights from the Experts: How PHP Leaders Are Transforming High-Impact PHP A...
Insights from the Experts: How PHP Leaders Are Transforming High-Impact PHP A...Insights from the Experts: How PHP Leaders Are Transforming High-Impact PHP A...
Insights from the Experts: How PHP Leaders Are Transforming High-Impact PHP A...
 
Solving the C20K problem: Raising the bar in PHP Performance and Scalability
Solving the C20K problem: Raising the bar in PHP Performance and ScalabilitySolving the C20K problem: Raising the bar in PHP Performance and Scalability
Solving the C20K problem: Raising the bar in PHP Performance and Scalability
 
Joe Staner Zend Con 2008
Joe Staner Zend Con 2008Joe Staner Zend Con 2008
Joe Staner Zend Con 2008
 
Tiery Eyed
Tiery EyedTiery Eyed
Tiery Eyed
 
Make your PHP Application Software-as-a-Service (SaaS) Ready with the Paralle...
Make your PHP Application Software-as-a-Service (SaaS) Ready with the Paralle...Make your PHP Application Software-as-a-Service (SaaS) Ready with the Paralle...
Make your PHP Application Software-as-a-Service (SaaS) Ready with the Paralle...
 
DB2 Storage Engine for MySQL and Open Source Applications Session
DB2 Storage Engine for MySQL and Open Source Applications SessionDB2 Storage Engine for MySQL and Open Source Applications Session
DB2 Storage Engine for MySQL and Open Source Applications Session
 
Digital Identity
Digital IdentityDigital Identity
Digital Identity
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Kürzlich hochgeladen (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

Lesser Known Security Problems in PHP Applications

  • 1. Lesser Known Security Problems in PHP Applications Stefan Esser Zend Conference September 2008 Santa Clara, CA
  • 2. The Speaker Stefan Esser • 8 years of PHP Core Experience • 10 years of Security Experience • Suhosin and The Month of PHP Bugs • Founder and Head of R&D at SektionEins GmbH Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  2
  • 3. Topics • Lesser Known Security Problems • Less Obvious Exploitation Paths • Inter Application Exploitation • Vulnerability Classes Discovered during Real Audits Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  3
  • 4. The Mantra... • Filter Input, Escape Output • often misunderstood • vulnerabilities hidden in input filters • wrong escaping / encoding functions • not every vulnerability is caused by tainted data Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  4
  • 5. Input Filtering - Short reminder • Filter what you actually use and not what you believe is the same <?php // The TikiWiki approach to input filtering if (!is_numeric($_REQUEST[‘id‘])) { die(‘Hack attack‘); // <-- will discuss this later } ... $_REQUEST = array_merge($_COOKIE, $_GET, $_POST); // ^----- really bad idea: GPC != CGP ?> Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  5
  • 6. $_SERVER and URL Encoding • PHP_SELF and REQUEST_URI often used • assumed to be URL encoded, but • PHP_SELF is never encoded (typical XSS) • REQUEST_URI encoding depends on client <?php if ($_SERVER[‘REQUEST_URI‘] == ‘common.php‘) { die(“do not call this file directly“); } // File can still be requested by common%2ephp ?> Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  6
  • 7. $_REQUEST and Cookies • never forget $_REQUEST also contains cookie data • cookies or cookie data might be unexpected • injected through XSS, HTTP Response Splitting or other cross domain browser bug • TLD wide cookies - *.co.uk / *.co.kr • originating from another application on same domain Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  7
  • 8. $_REQUEST and Cookie DOS • An injected cookie might kill the application <?php // one cookie to kill them all if (isset($_REQUEST[‘GLOBALS‘])) { die(‘GLOBALS overwrite attempt‘); } ?> Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  8
  • 9. $_REQUEST and Delayed CSRF • An injected cookie manipulates/overrides the control flow of a request performed by the user • Traditional CSRF protections useless <?php // save only modified admin options foreach ($_REQUEST[‘options‘] as $key => $val) { if (isset($options[$key]) && $options[$key] != $val) { saveOption($key, $val); } } // Because options[includePath] could be an evil cookie // there is a Delayed CSRF vulnerability // that allows remote file inclusion ?> Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  9
  • 10. auto_globals_jit - Documentation ; When enabled, the SERVER and ENV variables are created when they're first ; used (Just In Time) instead of when the script starts. If these variables ; are not used within a script, having this directive on will result in a ; performance gain. The PHP directives register_globals, register_long_arrays, ; and register_argc_argv must be disabled for this directive to have any affect. infamous documentation in php.ini Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  10
  • 11. auto_globals_jit - Open Questions • Documentation is correct ? - Almost definitely maybe (probably) - Ok, no • What about $_REQUEST ? • Is JIT really just-in-time of first usage ? Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  11
  • 12. auto_globals_jit - Reality • Documentation is wrong • There is no just-in-time creation on first usage • auto_globals are usually created before the start of the script if the compiler detects their usage • or when an extension requests their creation • The compiler just detects direct usage • access by variable-variables is NOT detected Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  12
  • 13. auto_globals_jit - Security Problem • prepended input filtering using variable-variables FAILS • auto_globals do not exist when the filter executes <?php $filterTargets = array(‘_REQUEST‘, ‘_SERVER‘, ‘_ENV‘, ...); foreach ($filterTargets as $target) { $$target = filterRecursive((array)$$target); } ?> • when a PHP script accesses the auto_globals they are created and filled with the not filtered values Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  13
  • 14. Session Handling - Insecure Cookie Parameters • very very common problem • sites use SSL to protect against session identifier sniffing • but forgets to mark session identifier cookie as secure • attacker injects HTTP requests to get plaintext cookie Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  14
  • 15. Session Handling - Session Data Mixup (I) • session data is stored in /tmp by default • can be changed by configuration • session data is shared by all applications that store it in the same location • bad for shared hosts • but can also lead to inter application exploits Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  15
  • 16. Session Handling - Session Data Mixup (II) • Example 1 - Setup: • customer runs two applications on his own server • both applications contain multi-step forms • both applications store data of previous steps in a session • application 1 merges user input into the session and validates/filters after all steps are processed • application 2 merges only validated and filtered data into the session Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  16
  • 17. Session Handling - Session Data Mixup (III) • Example 1 - Exploit: • enter malicious content (XSS, SQL Inj.) into application 1 • copy session identifier of application 1 into session cookie of application 2 • use application 2 which trust everything within the session ➡ XSS payload from session eventually exploits application 2 Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  17
  • 18. Session Handling - Session Data Mixup (IV) • Example 2 - Setup: • customer runs two applications on his own server • both applications serve a separate group of users • both applications are written by the same developers • both applications share a similar implementation Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  18
  • 19. Session Handling - Session Data Mixup (V) • Example 2 - Exploit: • attacker is a legit user of application 1 (maybe even a moderator / admin) • attacker logs himself into application 1 • and copies his session identifier into the session cookie of application 2 • because the implementation of the User object is shared, application 2 finds a valid User object in its session • attacker is now logged into application 2 Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  19
  • 20. Session Handling - Session Data Mixup (V) • Best Practices • store session data in different locations ➡ ini_set(“session.save_path“, “/tmp/application_1/“); ➡ user space session handler • embed application marker into the session ➡ if ((string)$_SESSION[‘application‘] !== ‘application_1‘) die(); • encrypt session data with application specific keys Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  20
  • 21. Session Handling - Insecure Transactions (I) • some PHP applications choose to override the internal session management with a user space session handler - usual implementation • open - ignored • read - SELECT * FROM tb_sessions WHERE sid=:sid • write - INSERT/UPDATE tb_sessions SET data=:data WHERE sid=:sid • close - ignore • destroy - ignore Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  21
  • 22. Session Handling - Insecure Transactions (II) • Usual implementation ignores that reading, updating and storing the session data forms a transaction • Most applications with user space session handlers are vulnerable to session race conditions Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  22
  • 23. Database Handling - Status Quo • SQL Injection widely known • SQL Transactions less known and used • SQL Errors are seldomly handled • Input filters let overlong input through Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  23
  • 24. Database Handling - MySQL‘s max_packet_size • max_packet_size configures maximum size of a packet • anything bigger will not be sent • overlong input can result in queries not being sent • allows e.g. disabling logging queries • referer header • user-agent header • session-identifiers, ... Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  24
  • 25. Database Handling - Truncated Data • database columns have a maximum width • by default MySQL will truncate any data that doesn‘t fit from ‘admin x‘ to ‘admin ‘ • by default string comparision will ignore trailing spaces ➡ Security Problem because there are 2 admin users now Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  25
  • 26. Database Handling - Best Practices • Use database transactions for application transactions • Handle errors, assume everything could fail • Use MySQL‘s sql_mode STRICT_ALL_TABLES • Catch overlong input in input filtering Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  26
  • 27. Multi-Byte Encodings - A security problem? • PHP uses backslash escaping in many places ➡ ( => , ‘ => ‘, “ => “ ) • backslash escaping is a problem for multi-byte parsers if the encoding allows backslashes as 2nd, 3rd, ... byte • UTF-8 not affected, but several asian encodings like GBK, EUC-KR, SJIS, ... SELECT * FROM u WHERE login='X' OR id=1/*' AND pwd='XXXXXXXXXX' will be parsed as SELECT * FROM u WHERE login='X' OR id=1/*' AND pwd='XXXXXXXXXX' Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  27
  • 28. Multi-Byte Encodings - Still a problem • SQL-Injection • mysql_real_escape_string() not safe when SET NAMES is used • Shell-Command Injection • PHP <= 5.2.6 doesn‘t escape shell commands for MB-locales • Eval/Preg-Replace/Create_Function Injection • PHP doesn‘t escape correctly for zend_multibyte mode • PHP Cache/Config Injection • var_export() doesn‘t escape correctly for zend_multibyte mode Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  28
  • 29. Multi-Byte Encodings - Special Case UTF-7 • UTF-7 is a 7 bit wide encoding • Characters used -+A-Za-z0-9 • not handled by any of PHP‘s escape functions • browsers can be tricked to parse pages as UTF-7 when no charset is given ➡ XSS vulnerabilities (also common on banking sites) Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  29
  • 30. Random Numbers • Random Number Generators • srand() / rand() • Wrapper around libc‘s rand() - 32 bit Seed • mt_srand() / mt_rand() • Mersenne Twister - 32 bit Seed • uniqid(?, true) / lcg_value() • Combined linear congruential generator - weak 64 bit Seed Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  30
  • 31. mt_srand() / srand() - weak seeding • PHP seeds automatically since 4.2.0 • Disadvantages of manual seeding • random number generator state is easier to predict • seeding influences other applications • manual seeding usually weaker than PHP‘s seeding <?php // examples for very bad seedings mt_srand(time()); mt_srand(microtime() * 100000); mt_srand(microtime() * 1000000); mt_srand(microtime() * 10000000); //<- Joomla Password Reset ?> Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  31
  • 32. mt_srand() / srand() - Automatic seeding • Automatic seeding in PHP <= 5.2.5 • time(0) * PID * 1000000 * php_combined_lcg() • on 32bit systems • lower bits of time(0) and PID can be controlled • due to modular arithmethic product is 0 every 2.1 years • on 64bit systems • precision loss during double to int conversion • strength around 24 bits Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  32
  • 33. mt_rand() / rand() - weak random numbers • numbers depend only on 32 bit seed and running time • not suited for cryptographic secrets • output of PRNG might leak state • state is process-wide => PRNG is shared resource • attacker can get fresh seed by crashing PHP Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  33
  • 34. mt_(s)rand / (s)rand - Shared Hosting • CGI • PRNG freshly seeded for every request • running time not necessary for prediction • mod_php / fastcgi • PRNG is shared for requests handled by same process • e.g. Keep-Alive • Sharing across VHOSTS • mean customer can seed PRNG to attack others Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  34
  • 35. mt_(s)rand / (s)rand - Cross Application Attacks • applications share the same PRNG • leak in one application allows attacking another • seeding in one application allows attacking another • phpBB2 seeds random number generator and leaks state • allows predicting password reset feature in Wordpress Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  35
  • 36. mt_(s)rand / (s)rand - Best Practices • do not seed the PRNGs • do not use PHP‘s PRNGs for cryptographic secrets • do not directly output random numbers • combine output of different PRNGs • use /dev/(u)random on unix systems Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  36
  • 37. PHP‘s ZipArchive • 0-day Vulnerability in PHP • exposed by applications using ZipArchive • discovered during an audit of customer code • reported 85 days ago to PHP‘s security response team • unpacking a malicious ZIP can overwrite any file • Exploit: just name archived files like ../../../../../www/hack.php Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  37
  • 38. HTTP Header Response Splitting/Suppression • Protection against HTTP Response Splitting • introduced with PHP 5.1.2 • not sufficient for old Netscape Proxies • suppresses headers containing recognized attacks • allows suppressing HTTP headers • security problem when Content-Disposition: attachment is suppressed Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  38
  • 39. The End ?!? There are more unusual, lesser known and dangerous vulnerabilities, but we are running out of time... Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  39
  • 40. Thank you for listening QUESTIONS ??? Stefan Esser • Lesser Known Security Problems in PHP Applications •  2008/Sep/17 •  40