SlideShare une entreprise Scribd logo
1  sur  40
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Tendances (20)

How to develop a gateway service using code based implementation
How to develop a gateway service using code based implementationHow to develop a gateway service using code based implementation
How to develop a gateway service using code based implementation
 
IBM API Connect - overview
IBM API Connect - overviewIBM API Connect - overview
IBM API Connect - overview
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening KeynoteClean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
 
Mule Common Logging & Error Handling Framework
Mule Common Logging & Error Handling FrameworkMule Common Logging & Error Handling Framework
Mule Common Logging & Error Handling Framework
 
Disaster Recovery Site on AWS - Minimal Cost Maximum Efficiency (STG305) | AW...
Disaster Recovery Site on AWS - Minimal Cost Maximum Efficiency (STG305) | AW...Disaster Recovery Site on AWS - Minimal Cost Maximum Efficiency (STG305) | AW...
Disaster Recovery Site on AWS - Minimal Cost Maximum Efficiency (STG305) | AW...
 
(DAT407) Amazon ElastiCache: Deep Dive
(DAT407) Amazon ElastiCache: Deep Dive(DAT407) Amazon ElastiCache: Deep Dive
(DAT407) Amazon ElastiCache: Deep Dive
 
Session on API auto scaling, monitoring and Log management
Session on API auto scaling, monitoring and Log managementSession on API auto scaling, monitoring and Log management
Session on API auto scaling, monitoring and Log management
 
A comprehensive guide to mule soft mule 4
A comprehensive guide to mule soft mule 4A comprehensive guide to mule soft mule 4
A comprehensive guide to mule soft mule 4
 
Microservice Approach for Web Development with Micro Frontends
Microservice Approach for Web Development with Micro FrontendsMicroservice Approach for Web Development with Micro Frontends
Microservice Approach for Web Development with Micro Frontends
 
AWSome Day Online Conference 2019 - Module 1 AWS Cloud Concepts.pdf
AWSome Day Online Conference 2019 - Module 1 AWS Cloud Concepts.pdfAWSome Day Online Conference 2019 - Module 1 AWS Cloud Concepts.pdf
AWSome Day Online Conference 2019 - Module 1 AWS Cloud Concepts.pdf
 
Java Web 程式之效能技巧與安全防護
Java Web 程式之效能技巧與安全防護Java Web 程式之效能技巧與安全防護
Java Web 程式之效能技巧與安全防護
 
[AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵
 [AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵 [AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵
[AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵
 
Anypoint platform architecture and components
Anypoint platform architecture and componentsAnypoint platform architecture and components
Anypoint platform architecture and components
 
Performance Modeling of Serverless Computing Platforms - CASCON2020 Workshop ...
Performance Modeling of Serverless Computing Platforms - CASCON2020 Workshop ...Performance Modeling of Serverless Computing Platforms - CASCON2020 Workshop ...
Performance Modeling of Serverless Computing Platforms - CASCON2020 Workshop ...
 
Best Practices for SecOps on AWS
Best Practices for SecOps on AWSBest Practices for SecOps on AWS
Best Practices for SecOps on AWS
 
Running and Managing Mule Applications
Running and Managing Mule ApplicationsRunning and Managing Mule Applications
Running and Managing Mule Applications
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
Oop principles
Oop principlesOop principles
Oop principles
 
Bootstrapping Clusters with EKS Blueprints.pptx
Bootstrapping Clusters with EKS Blueprints.pptxBootstrapping Clusters with EKS Blueprints.pptx
Bootstrapping Clusters with EKS Blueprints.pptx
 

Similaire à 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
 

Similaire à 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
 

Plus de ZendCon

Plus de 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
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
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)
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - 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
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

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