flawopen.com/command-injection/C-cpp
Learn how to fix Command Injection (CWE-78) in C and C++. Side-by-side vulnerable vs secure code examples for posix_spawn(), execvp(), and system() shell hazards.
想象一下,你让办公室助理打印一份名为 'report.pdf' 的文件。当有人恶意提供文件名 'report.pdf; whoami' 时,助理不加检查地将整张便签递给终端窗口,导致系统不仅打印文件,还读取了管理员工作证。
Web Application SecurityCWE-918.CWE-918CWE-918):Standard Common Weakness Enumeration classification for command-injection-c-cpp.Defense-in-Depth应用程序直接通过 HTTP 请求或表单接收用户提供的诊断主机名、文件名或工具参数。
后端通过原始字符串拼接构建系统命令字符串,而未采用参数化参数列表(Argument Vector)。
攻击者输入包含 Shell 元字符(如 ';', '&&', '|', 反引号)的载荷(如 '127.0.0.1; id'),逃逸预期命令范围。
底层操作系统 Shell 以 Web 进程权限执行注入的后续命令,造成远程命令执行与系统接管。
// system() invokes /bin/sh with sprintf buffer
#include <stdlib.h>
#include <stdio.h>
void ping_host(const char *user_input) {
char buffer[256];
// Attacker input: "127.0.0.1; reboot"
snprintf(buffer, sizeof(buffer), "ping -c 1 %s", user_input);
system(buffer);
}
// fork() and execvp() execute binary directly without a shell
#include <unistd.h>
#include <sys/wait.h>
void ping_host(const char *user_input) {
pid_t pid = fork();
if (pid == 0) {
// Child process: arguments are discrete pointers
char *args[] = {"ping", "-c", "1", (char *)user_input, NULL};
execvp("ping", args);
_exit(1);
} else {
waitpid(pid, NULL, 0);
}
}
system() and popen() with fork() and execvp()。