Operating System Command Injection

Operating system command injection in C/C++

Description

system(), popen(), and _popen() pass a string to a command interpreter, as does C++'s std::system() from <cstdlib>. If the string includes untrusted input, shell metacharacters, command separators, redirections, or additional arguments may be interpreted as code. wordexp() also performs shell word expansion and can execute command substitutions unless WRDE_NOCMD is specified.

Escaping shell characters alone cannot safely handle every shell and target program's syntax. Even when shell commands are blocked, argument injection may remain if the target program treats untrusted values as options. A helper name such as shell_escape() or sanitize_command_arg() does not establish safety.

Potential impact

  • Arbitrary operating system commands may run with the application's privileges.
  • Consequences can include file deletion or modification, sensitive data exposure, internal system access, and service disruption.
  • A highly privileged process may expose the entire system to compromise.

Remediation

Use a library API for the task when possible. If you need a separate process, launch it directly.

  1. Fix the executable path in code. On POSIX, pass it and a separate argument array to execve() or posix_spawn(). With Windows CreateProcessW(), set lpApplicationName to the fixed path and pass a separate writable lpCommandLine buffer formatted for the target program.
  2. Validate each argument against the format the target program expects. Check how it handles a leading - and whether it supports -- to end options.
  3. Set only the environment variables the process needs, using trusted values. Handle errors from the process API.

If you need wordexp(), pass WRDE_NOCMD and check its return value. A request for command substitution returns WRDE_CMDSUB. Other word expansions still need to be checked.

Examples

C

Before

c
#include <stdlib.h>

int main(int argc, char **argv) {
    if (argc != 2) {
        return 2;
    }

    return system(argv[1]);
}

After

c
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

static int valid_label(const char *value) {
    size_t length = strlen(value);
    if (length == 0 || length > 64) {
        return 0;
    }

    for (size_t i = 0; i < length; ++i) {
        unsigned char ch = (unsigned char)value[i];
        if (!isalnum(ch) && ch != '.' && ch != '_' && ch != '-') {
            return 0;
        }
    }
    return 1;
}

int main(int argc, char **argv) {
    if (argc != 2 || !valid_label(argv[1])) {
        return 2;
    }

    char *const args[] = {"printf", "Archive: %s\n", argv[1], NULL};
    execv("/usr/bin/printf", args);
    perror("execv");
    return 1;
}

execv() starts /usr/bin/printf with a fixed format string. The validated label is a separate argument.

This wordexp() wrapper disables command substitution and checks for errors.

c
#include <wordexp.h>

int expand_without_commands(const char *input, wordexp_t *words) {
    int result = wordexp(input, words, WRDE_NOCMD | WRDE_UNDEF);
    if (result != 0) {
        if (result == WRDE_NOSPACE) {
            wordfree(words);
        }
        return -1;
    }
    return 0;
}

After success, the caller releases the result with wordfree(). On WRDE_NOSPACE, the wrapper calls wordfree() to release any partial allocation.

C++

Before

cpp
#include <cstdlib>

int main(int argc, char **argv) {
    if (argc != 2) {
        return 2;
    }

    return std::system(argv[1]);
}

After

cpp
#include <cctype>
#include <cstdio>
#include <cstring>
#include <unistd.h>

static bool valid_label(const char *value) {
    std::size_t length = std::strlen(value);
    if (length == 0 || length > 64) {
        return false;
    }

    for (std::size_t i = 0; i < length; ++i) {
        unsigned char ch = static_cast<unsigned char>(value[i]);
        if (!std::isalnum(ch) && ch != '.' && ch != '_' && ch != '-') {
            return false;
        }
    }
    return true;
}

int main(int argc, char **argv) {
    if (argc != 2 || !valid_label(argv[1])) {
        return 2;
    }

    char program[] = "/usr/bin/printf";
    char format[] = "Archive: %s\n";
    char *const args[] = {program, format, argv[1], nullptr};
    execv(program, args);
    std::perror("execv");
    return 1;
}

The C++23 example uses POSIX.1-2024 execv() to run the fixed program. valid_label() checks the argument before it is passed to the program.

References