SlideShare a Scribd company logo
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

More Related Content

Similar to 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 5Stephan 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 Appelliando 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
 
Profiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / WebgrindProfiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / Webgrind
Sam Keen
 
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 praguehernanibf
 
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
Jérémy Derussé
 
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
guest3379bd
 
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
Max Małecki
 
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
Zend by Rogue Wave Software
 
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
360|Conferences
 
Web backdoors attacks, evasion, detection
Web backdoors   attacks, evasion, detectionWeb backdoors   attacks, evasion, detection
Web backdoors attacks, evasion, detection
n|u - The Open Security Community
 
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
Michael Spector
 
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
Vladyslav Radetsky
 
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
 
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
Wim Godden
 
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
Emtec Inc.
 
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!
Jeff Jones
 
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
Wim Godden
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life better
ZendCon
 
Symfony 2.0
Symfony 2.0Symfony 2.0
Symfony 2.0
GrUSP
 

Similar to Lesser Known Security Problems in PHP Applications (20)

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
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life better
 
Symfony 2.0
Symfony 2.0Symfony 2.0
Symfony 2.0
 

More from ZendCon

Framework Shootout
Framework ShootoutFramework Shootout
Framework Shootout
ZendCon
 
Zend_Tool: Practical use and Extending
Zend_Tool: Practical use and ExtendingZend_Tool: Practical use and Extending
Zend_Tool: Practical use and Extending
ZendCon
 
PHP on IBM i Tutorial
PHP on IBM i TutorialPHP on IBM i Tutorial
PHP on IBM i Tutorial
ZendCon
 
PHP on Windows - What's New
PHP on Windows - What's NewPHP on Windows - What's New
PHP on Windows - What's New
ZendCon
 
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
ZendCon
 
I18n with PHP 5.3
I18n with PHP 5.3I18n with PHP 5.3
I18n with PHP 5.3
ZendCon
 
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
ZendCon
 
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
ZendCon
 
Magento - a Zend Framework Application
Magento - a Zend Framework ApplicationMagento - a Zend Framework Application
Magento - a Zend Framework Application
ZendCon
 
Enterprise-Class PHP Security
Enterprise-Class PHP SecurityEnterprise-Class PHP Security
Enterprise-Class PHP Security
ZendCon
 
PHP and IBM i - Database Alternatives
PHP and IBM i - Database AlternativesPHP and IBM i - Database Alternatives
PHP and IBM i - Database Alternatives
ZendCon
 
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
ZendCon
 
Application Diagnosis with Zend Server Tracing
Application Diagnosis with Zend Server TracingApplication Diagnosis with Zend Server Tracing
Application Diagnosis with Zend Server Tracing
ZendCon
 
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...
ZendCon
 
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
ZendCon
 
Joe Staner Zend Con 2008
Joe Staner Zend Con 2008Joe Staner Zend Con 2008
Joe Staner Zend Con 2008
ZendCon
 
Tiery Eyed
Tiery EyedTiery Eyed
Tiery Eyed
ZendCon
 
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...
ZendCon
 
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
ZendCon
 
Digital Identity
Digital IdentityDigital Identity
Digital Identity
ZendCon
 

More from 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
 

Recently uploaded

Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 

Recently uploaded (20)

Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 

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