flawopen.com/command-injection/C-cpp

● CWE-918 · Critique
Recherche · FlawOpen

Command Injection in C/C++

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.

💡 Explication en Langage Simple (ELI5)

Imaginez demander à un assistant de bureau d'imprimer un document nommé 'rapport.pdf'. L'injection de commande se produit lorsque quelqu'un fournit le nom 'rapport.pdf; whoami', et l'assistant transmet aveuglément le billet au terminal, imprimant le rapport et lisant le badge d'administrateur.

Concepts Clés et Termes

Web Application Security
Composant d'architecture clé affecté par CWE-918.
CWE-918
Classification standard Common Weakness Enumeration (CWE) pour command-injection-c-cpp.
Defense-in-Depth
Vérification d'ingénierie multicouche et isolation des limites à l'exécution.

Déroulement de l'Attaque Étape par Étape

Step 1

Ingestion de Paramètres Non Fiables

L'application reçoit des noms d'hôte de diagnostic ou des noms de fichiers directement à partir d'une requête HTTP.

Step 2

Interpolation Shell Non Sécurisée

Le backend assemble une commande shell par simple concaténation de chaînes au lieu d'utiliser un tableau d'arguments isolé.

Step 3

Injection de Séparateur de Commandes

L'attaquant injecte des métacaractères shell comme ';', '&&', '|' ou des accents graves (ex. '127.0.0.1; id') pour échapper au contexte initial.

Step 4

Exécution en Sous-shell et Compromission

Le shell du système d'exploitation exécute la commande injectée avec tous les privilèges du processus du serveur web.

Code Source : Vulnérable vs Sécurisé

✕ IMPLÉMENTATION VULNÉRABLE
// 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);
}
✓ PATCH SÉCURISÉ ET ROBUSTE
// 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);
    }
}

Liste de Contrôle de Sécurité pour l'Ingénierie

References