Secure Coding in C · intermediate · ~10 min

Command injection prevention

Never run a shell on user input.

Lesson

system("cmd " + user_data) invokes /bin/sh, which interprets ;, &&, backticks, $() etc. Attacker types ; rm -rf / and you have a problem.

Replacement: fork + execvp with an explicit argv array. The shell is bypassed; user data stays a single argument.

Code examples

// BAD
char cmd[256]; snprintf(cmd, sizeof cmd, "echo %s", user);
system(cmd);

// GOOD
pid_t p = fork();
if (p == 0) {
    char *argv[] = { "echo", (char*)user, NULL };
    execvp("echo", argv); _exit(127);
}
waitpid(p, NULL, 0);