Rules / C/C++
SHIELD-CPP-009
Command injection via popen
What it detects
popen with a variable or concatenated command string can execute injected shell commands.
How to fix
Replace popen with a direct exec of a fixed program and sanitized arguments.
Vulnerable — Shield flags thislist.c
#include <stdio.h>
void list_dir(const char *dir) {
char cmd[128];
snprintf(cmd, sizeof(cmd), "ls -l %s", dir);
FILE *fp = popen(cmd, "r");
if (fp) pclose(fp);
}
Fixed — scans cleanlist.c
#include <unistd.h>
void list_dir(const char *dir) {
char *const argv[] = {"/bin/ls", "-l", (char *)dir, NULL};
execv("/bin/ls", argv);
}
Both snippets are verified against the shipped scanner: the vulnerable one triggers SHIELD-CPP-009, the fixed one does not.