flawopen.com/command-injection/C-cpp

● CWE-918 · 심각
보안 연구 · 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.

💡 알기 쉬운 설명 (ELI5)

사무실 보조원에게 'report.pdf'라는 문서를 인쇄해 달라고 요청하는 상황을 상상해 보세요. 누군가 'report.pdf; whoami'라는 파일명을 적어주면, 보조원이 그 메모 전체를 터미널 창구에 그대로 전달하여 보고서 인쇄와 동시에 관리자 배지 정보까지 읽어버리는 취약점입니다.

핵심 개념 및 용어

Web Application Security
보안 개념 (Web Application Security): Core architecture component affected by CWE-918.
CWE-918
보안 개념 (CWE-918): Standard Common Weakness Enumeration classification for command-injection-c-cpp.
Defense-in-Depth
보안 개념 (Defense-in-Depth): Multi-layered engineering verification and runtime boundary isolation.

단계별 공격 실행 흐름

Step 1

신뢰할 수 없는 매개변수 수신

애플리케이션이 HTTP 요청을 통해 진단용 호스트명, 파일명 등의 입력을 직접 전달받습니다.

Step 2

안전하지 않은 셸 명령어 문자열 결합

백엔드가 독립된 인자 배열을 사용하지 않고 원시 문자열 결합으로 셸 명령을 구성합니다.

Step 3

명령어 구분자 삽입

공격자가 ';', '&&', '|', 백틱 등의 메타문자(예: '127.0.0.1; id')를 주입하여 기존 구문을 탈출합니다.

Step 4

서브셸 실행 및 호스트 장악

운영체제 셸이 웹 프로세스 권한으로 추가 주입된 명령을 실행하여 원격 코드 실행이 발생합니다.

소스 코드 비교: 취약한 구현 vs 보안 패치

✕ 취약한 구현
// 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);
    }
}

엔지니어링 및 시스템 보안 강화 체크리스트

References