今日表示しない

トップへ戻る

トップへ戻る

脆弱性研究

脆弱性研究

脆弱性研究

Vulnerability Analysis of NGINX2Shell and Four NGINX RCE

Vulnerability Analysis of NGINX2Shell and Four NGINX RCE

Vulnerability Analysis of NGINX2Shell and Four NGINX RCE

엔키화이트햇

엔키화이트햇

コンテンツ

コンテンツ

コンテンツ

1. 개요

nginx는 국내외에서 널리 쓰이는 웹 서버다. HTTP/1.1뿐 아니라 HTTP/2와 HTTP/3(QUIC)까지 지원하고, 리버스 프록시로서 서비스의 가장 앞단을 맡는 경우가 많다. 2026년 11월 18일 F5는 nginx 1.31.9(mainline)와 1.30.7(stable)을 내놓으며 worker 프로세스의 메모리를 손상시키는 취약점 5개를 함께 수정했다. 이 가운데 HTTP/2 흐름 제어 결함인 CVE-2026-123007은 NGINX2Shell이라는 이름으로 알려졌으며 나머지 4개는 HTTP/2·HTTP/3 연결 관리, 내장 리졸버, 메일 프록시에서 발생하는 use-after-free로, 이들 역시 원격 코드 실행(RCE)으로 이어질 수 있다.

caption - nginx2shell f5 보안공지

F5 보안 공지는 5개 모두에 CVSS 3.1 기준 8.1점, CVSS 4.0 기준 9.2점을 부여했다. 인증 없는 원격 공격자가 worker를 재시작시키거나 메모리를 손상시킬 수 있으며, ASLR이 꺼져 있거나 우회되면 코드 실행까지 가능하다.

CVE

영향 영역

약점 유형

영향 버전(OSS)

필요한 설정

CVE-2026-123007 (NGINX2Shell)

HTTP/2 흐름 제어

CWE-191, CWE-787

1.9.5–1.31.8

HTTP/2 활성화

CVE-2026-123633

HTTP/2 연결 재사용·drain

CWE-416

1.19.7–1.31.8

HTTP/2 + 백엔드 전달

CVE-2026-121810

HTTP/3(QUIC) 연결 재사용

CWE-416

1.25.0–1.31.8

HTTP/3 + 백엔드 전달

CVE-2026-123634

내장 resolver

CWE-416

0.6.18–1.31.8

resolver + 변수 proxy_pass + mirror(mirror_request_body off)/SSI

CVE-2026-113425

메일 프록시 auth_http

CWE-416

0.5.33–1.31.8

mail + proxy on + auth_http

다만 취약점 노출 여부는 nginx 버전만으로 결정되지 않는다. 표의 '필요한 설정'처럼 취약점마다 켜져 있어야 하는 기능이 다르기 때문이다. NGINX2Shell만 놓고 보면 HTTP/2를 끈 서버는 공격할 수 없다. HTTP/2가
켜져 있더라도 CDN이나 WAF가 앞단에서 HTTP/2를 종단하는 구조라면 공격 프레임이 원 서버까지 그대로 전달되지 않으므로 공격이 어려울 수 있다. 익스플로잇 자체의 비용도 적지 않다. Rapid7이 공개한 PoC 기준으로
약 128GB의 HTTP/2 트래픽이 필요하고, 대역폭에 따라 2분에서 1시간이 소요된다. nginx의 기본 연결 유지 시간(1시간) 안에 완료해야 하므로 느린 경로에서는 성립하지 않을 수 있으며, 현재 공개된 기법은 x86-64
빌드의 glibc memcpy 구현에 의존한다.

이 글에서는 각 취약점의 기술적 배경과 근본 원인을 공격 과정과 함께 알아보고 취약점 조치를 어떻게 해야 하는지 안내하겠다.

2. 기술적 배경

이 장에서는 5개 취약점의 분석에 필요한 공통 배경을 정리한다. HTTP/2 프로토콜의 프레임 구조와 흐름 제어는 CVE-2026-123007을 이해하는 데 필수적이며, nginx의 연결 슬롯 관리와 drain 메커니즘은 CVE-2026-123633과 CVE-2026-121810에서 공통으로 사용된다. 나머지 CVE에 고유한 배경(리졸버, 메일 프록시 등)은 해당 절에서 별도로 다룬다.

2.1 HTTP/2 프레임과 스트림

HTTP/2에서 모든 통신은 frame이라는 단위로 오간다. 하나의 frame은 9바이트 header와 그 뒤에 이어지는 payload로 구성되며, header에는 payload 길이, frame 종류(Type), 플래그, 그리고 이 frame이 어느 stream에 속하는지를 나타내는 31비트 Stream Identifier가 담긴다.

필드

크기

의미

Length

24 bit

payload 길이(header 9바이트 제외). 기본 최대 16,384바이트

Type

8 bit

frame 종류

Flags

8 bit

type별 플래그 (END_STREAM 0x1, END_HEADERS 0x4 등)

R

1 bit

예약 비트, 항상 0

Stream Identifier

31 bit

frame이 속한 stream. 0이면 connection 전체에 대한 frame

stream은 connection 안의 논리적 채널이다. 요청-응답 한 쌍이 stream 하나를 쓰며, client가 여는 stream에는 홀수 ID(1, 3, 5, …)가 붙는다. Stream ID 0은 특정 요청이 아니라 connection 자체를 가리킨다. 모든 frame에 stream ID가 붙어 있으므로 한 connection 위에서 여러 stream의 frame을 섞어 보낼 수 있고, 이것이 HTTP/2의 multiplexing이다.

frame은 10종류가 있는데, 이 취약점과 직접 관련되는 것은 여섯 가지다.

Type

이름

용도

0x0

DATA

응답/요청 body 전달. flow control 대상인 유일한 frame

0x1

HEADERS

헤더 블록 전달. 요청·응답의 시작

0x3

RST_STREAM

stream 하나를 즉시 취소

0x4

SETTINGS

connection 파라미터 교환

0x7

GOAWAY

connection 종료 예고

0x8

WINDOW_UPDATE

flow control window 증가. Stream ID 0이면 connection 전체, 아니면 해당 stream

2.2 HTTP/2 흐름 제어

HTTP/2는 TCP의 flow control 위에 자체적인 flow control을 한 층 더 둔다. 한 stream이 connection 대역폭을 독점하거나 수신 측 버퍼를 넘치게 하는 것을 방지하기 위해서다. flow control이 적용되는 대상은 DATA frame뿐이며, HEADERS나 PING 같은 제어 frame은 window를 소모하지 않는다.

window는 두 종류가 있다. 각 stream이 개별적으로 갖는 stream send window와, connection 전체에서 모든 stream이 공유하는 connection send window(Stream ID 0의 window)다. server가 DATA를 보내려면 해당 stream의 window와 connection window 양쪽 모두에 여유가 있어야 한다. 초기값은 둘 다 65,535바이트이고, 어느 쪽이든 최대 2^31−1(2,147,483,647)바이트를 넘을 수 없다. server가 DATA를 보내면 payload 크기만큼 양쪽 window가 줄어들고, client가 WINDOW_UPDATE frame을 보내면 지정한 양만큼 window가 늘어난다.

이 동작을 구체적인 예로 보면 다음과 같다. client가 stream 1로 80,000바이트짜리 파일을, stream 3으로 30,000바이트짜리 파일을 요청했다고 하자. 기본 설정(INITIAL_WINDOW_SIZE 65,535, MAX_FRAME_SIZE 16,384)에서 각 window의 변화를 추적한 것이다.

#

frame (방향)

stream 0

stream 1

stream 3

설명

0

시작

65,535

65,535

65,535

HEADERS로 stream 1, 3이 열리며 각자 초기값을 받음

1

DATA s1 16,384 (S→C)

49,151

49,151

65,535

DATA 하나가 stream 0과 stream 1을 동시에 차감

2

DATA s3 16,384 (S→C)

32,767

49,151

49,151

stream 3의 DATA도 같은 stream 0에서 차감

3

DATA s1 16,384 (S→C)

16,383

32,767

49,151

connection window가 빠르게 줄어듦

4

DATA s3 13,616 + END_STREAM (S→C)

2,767

32,767

35,535

stream 3 전송 완료

5

DATA s1 2,767 (S→C)

0

30,000

–

stream 1은 30,000이 남았지만 stream 0이 0이라 멈춤

6

WINDOW_UPDATE s0 +65,535 (C→S)

65,535

30,000

–

client가 connection window를 다시 채움

이 표에서 주목할 점이 세 가지 있다. 첫째, stream 0은 모든 stream이 함께 쓰는 공유 예산이다. 어느 stream으로 DATA를 보내든 stream 0의 window가 같이 줄어든다. 둘째, stream이 종료되어도 이미 소모한 connection window는 자동으로 돌아오지 않는다. 4번에서 stream 3이 끝났지만 stream 0은 그대로다. connection window를 회복하는 유일한 방법은 client가 보내는 Stream ID 0 WINDOW_UPDATE다. 셋째, WINDOW_UPDATE는 데이터를 받는 쪽이 보낸다. server가 응답을 보내는 방향에서는 client가 언제, 얼마만큼 window를 늘릴지 결정한다.

6번의 WINDOW_UPDATE frame을 바이트로 풀어 보면 다음과 같다.

WINDOW_UPDATE stream 0, +65,535
00 00 04   08   00   00 00 00 00   00 00 ff ff
Length=4   Type=0x8   Flags=0   Stream=0   Increment=0x0000FFFF
WINDOW_UPDATE stream 0, +65,535
00 00 04   08   00   00 00 00 00   00 00 ff ff
Length=4   Type=0x8   Flags=0   Stream=0   Increment=0x0000FFFF
WINDOW_UPDATE stream 0, +65,535
00 00 04   08   00   00 00 00 00   00 00 ff ff
Length=4   Type=0x8   Flags=0   Stream=0   Increment=0x0000FFFF

payload는 예약 비트 1개와 31비트 증가분으로 이루어진 4바이트다. 증가분이 31비트이므로 한 번에 늘릴 수 있는 최대치도 2^31−1이다.

한 가지 더 알아야 할 것이 SETTINGS_INITIAL_WINDOW_SIZE의 동작이다. 이 설정은 stream window의 초기값만 바꾸고, connection window는 건드리지 않는다. 이미 열린 stream에는 "새 값 − 옛 값"만큼을 더하거나 빼므로 stream window는 음수가 될 수도 있다. 가령 위 예시의 6번 직후에 client가 INITIAL_WINDOW_SIZE를 16,384로 줄이면, stream 1의 window는 30,000 − 49,151 = −19,151이 된다. 이것은 오류가 아니며, server는 window가 다시 양수가 될 때까지 해당 stream에 DATA를 보내지 않고 기다린다. 반면 connection window(stream 0)는 65,535 그대로다. 공격자가 SETTINGS_INITIAL_WINDOW_SIZE를 0으로 보내 모든 stream의 DATA 전송을 멈출 수 있으면서도 connection window에는 영향을 주지 않는다는 성질이, 뒤에서 익스플로잇의 출발점이 된다.

HTTP/2 규격은 window가 2^31−1을 넘는 상황에 대해 명확한 오류 처리를 규정하고 있다. WINDOW_UPDATE로 window가 상한을 넘으면 Stream ID 0인 경우 GOAWAY(connection error), 그 외에는 RST_STREAM(stream error)으로 FLOW_CONTROL_ERROR를 보내야 한다. 구현체가 이 상한 검사를 제대로 수행하지 않으면 window 값이 규격 범위를 벗어나고, 이후 그 값을 사용하는 모든 비교와 연산이 예상하지 못한 범위에서 수행된다.

상황

규격상 처리

DATA 전송

payload 크기를 stream window와 connection window 양쪽에서 차감

WINDOW_UPDATE 증가분이 0

Stream ID 0이면 connection error, 그 외면 stream error (PROTOCOL_ERROR)

WINDOW_UPDATE로 window가 2^31−1 초과

Stream ID 0이면 GOAWAY, 그 외면 RST_STREAM (FLOW_CONTROL_ERROR)

SETTINGS_INITIAL_WINDOW_SIZE로 stream window가 2^31−1 초과

connection error (FLOW_CONTROL_ERROR)

flow control은 connection 양 끝 사이에서만 의미가 있다(hop-by-hop). CDN이나 reverse proxy가 앞단에서 HTTP/2를 종단하면, client와의 window는 그 장비가 따로 관리하고 뒤쪽 nginx와는 별개의 연결을 맺는다. 개요에서 CDN·WAF가 HTTP/2를 종단하는 구조에서는 공격 frame이 nginx까지 그대로 전달되지 않는다고 한 것은 이 때문이다.

2.3 nginx 연결 관리

nginx 워커가 동시에 유지할 수 있는 연결 수는 worker_connections 지시어로 제한된다. 클라이언트 연결과 업스트림(백엔드) 연결이 같은 풀의 슬롯을 공유한다. 새 연결을 열 때 ngx_get_connection() 함수가 슬롯을 할당하는데, 여유 슬롯이 부족하면 이 함수 내부에서 ngx_drain_connections()가 호출된다.

nginx는 현재 활발히 사용되지 않는 연결을 reusable 연결 큐에 등록한다. HTTP/1.1 keep-alive 연결이나 활성 stream이 없는 HTTP/2 연결이 대표적이다. ngx_reusable_connection(c, 1)을 호출하면 큐의 맨 앞에 삽입되고, ngx_reusable_connection(c, 0)을 호출하면 큐에서 제거된다.

// src/core/ngx_connection.c — 1374~1401
void
ngx_reusable_connection(ngx_connection_t *c, ngx_uint_t reusable)
{
    if (c->reusable) {
        ngx_queue_remove(&c->queue);               // remove existing entry
        ngx_cycle->reusable_connections_n--;
    }

    c->reusable = reusable;

    if (reusable) {
        ngx_queue_insert_head(                      // insert at head of queue
            (ngx_queue_t *) &ngx_cycle->reusable_connections_queue, &c->queue);
        ngx_cycle->reusable_connections_n++;
    }
}
// src/core/ngx_connection.c — 1374~1401
void
ngx_reusable_connection(ngx_connection_t *c, ngx_uint_t reusable)
{
    if (c->reusable) {
        ngx_queue_remove(&c->queue);               // remove existing entry
        ngx_cycle->reusable_connections_n--;
    }

    c->reusable = reusable;

    if (reusable) {
        ngx_queue_insert_head(                      // insert at head of queue
            (ngx_queue_t *) &ngx_cycle->reusable_connections_queue, &c->queue);
        ngx_cycle->reusable_connections_n++;
    }
}
// src/core/ngx_connection.c — 1374~1401
void
ngx_reusable_connection(ngx_connection_t *c, ngx_uint_t reusable)
{
    if (c->reusable) {
        ngx_queue_remove(&c->queue);               // remove existing entry
        ngx_cycle->reusable_connections_n--;
    }

    c->reusable = reusable;

    if (reusable) {
        ngx_queue_insert_head(                      // insert at head of queue
            (ngx_queue_t *) &ngx_cycle->reusable_connections_queue, &c->queue);
        ngx_cycle->reusable_connections_n++;
    }
}

새로 등록된 연결은 큐의 앞쪽에 들어가고, drain은 큐의 뒤쪽(가장 오래된 것)부터 꺼내 닫는다.

여유 슬롯이 전체의 1/16 이하로 떨어지면, ngx_drain_connections()가 reusable 큐의 뒤쪽에서 연결을 꺼내 c->close = 1로 설정한 뒤 그 연결의 read handler를 직접 호출한다. 이 호출은 ngx_get_connection() 내부에서 동기적으로 실행된다. 새 연결 슬롯을 할당하려는 함수의 호출 스택 안에서 기존 연결의 read handler가 실행되는 구조다.

// src/core/ngx_connection.c — 1405~1442 (ngx_drain_connections)
if (cycle->free_connection_n > cycle->connection_n / 16
    || cycle->reusable_connections_n == 0)
{
    return;                                // enough free slots, nothing to do
}
/* ... */
n = ngx_max(ngx_min(32, cycle->reusable_connections_n / 8), 1);

for (i = 0; i < n; i++) {
    /* ... */
    q = ngx_queue_last(&cycle->reusable_connections_queue);
    c = ngx_queue_data(q, ngx_connection_t, queue);
    /* ... */
    c->close = 1;
    c->read->handler(c->read);            // directly invoke read handler to close
}
// src/core/ngx_connection.c — 1405~1442 (ngx_drain_connections)
if (cycle->free_connection_n > cycle->connection_n / 16
    || cycle->reusable_connections_n == 0)
{
    return;                                // enough free slots, nothing to do
}
/* ... */
n = ngx_max(ngx_min(32, cycle->reusable_connections_n / 8), 1);

for (i = 0; i < n; i++) {
    /* ... */
    q = ngx_queue_last(&cycle->reusable_connections_queue);
    c = ngx_queue_data(q, ngx_connection_t, queue);
    /* ... */
    c->close = 1;
    c->read->handler(c->read);            // directly invoke read handler to close
}
// src/core/ngx_connection.c — 1405~1442 (ngx_drain_connections)
if (cycle->free_connection_n > cycle->connection_n / 16
    || cycle->reusable_connections_n == 0)
{
    return;                                // enough free slots, nothing to do
}
/* ... */
n = ngx_max(ngx_min(32, cycle->reusable_connections_n / 8), 1);

for (i = 0; i < n; i++) {
    /* ... */
    q = ngx_queue_last(&cycle->reusable_connections_queue);
    c = ngx_queue_data(q, ngx_connection_t, queue);
    /* ... */
    c->close = 1;
    c->read->handler(c->read);            // directly invoke read handler to close
}

이 drain 메커니즘은 CVE-2026-123633과 CVE-2026-121810의 공통 원인이다. 연결이 reusable 큐에 잘못 남아 있으면, 그 연결 위에서 요청을 처리하는 도중 drain에 의해 연결이 닫힐 수 있고, 이후 해제된 메모리에 접근하면서 use-after-free가 발생한다.

3. NGINX2Shell(CVE-2026-123007) 상세 분석

NGINX2Shell이 공격하는 대상은 nginx가 응답을 보낼 때 사용하는 server→client 방향의 connection send window, 즉 h2c->send_window다.

공격자가 가장 먼저 하는 일은 HTTP/2 TLS 연결을 맺은 뒤, SETTINGS_INITIAL_WINDOW_SIZE를 0으로 설정하는 것이다. 이 값은 stream send window의 초기값만 바꾸고 connection send window에는 영향을 주지 않는다. stream send window가 0이 되면 nginx는 응답 HEADERS는 만들되 DATA는 보내지 못하게 되므로, 공격자는 큰 파일을 여러 stream으로 요청해 nginx가 응답을 준비하되 보내지는 못하는 상태를 만든다.

여기서 공격자는 각 stream에 WINDOW_UPDATE를 보내 stream send window를 연다. nginx는 비로소 DATA를 출력 큐에 넣을 수 있게 되고, 큐에 넣는 순간 connection send window에서 해당 frame 크기를 차감한다.

// src/http/v2/ngx_http_v2_filter_module.c — 1239~1244 (ngx_http_v2_send_chain)
ngx_http_v2_queue_frame(h2c, frame);     // enqueue DATA frame to output queue
h2c->send_window -= frame_size;          // subtract from connection send window
stream->send_window -= frame_size;       // subtract from stream send window
stream->queued++;                        // increment queued frame count
// src/http/v2/ngx_http_v2_filter_module.c — 1239~1244 (ngx_http_v2_send_chain)
ngx_http_v2_queue_frame(h2c, frame);     // enqueue DATA frame to output queue
h2c->send_window -= frame_size;          // subtract from connection send window
stream->send_window -= frame_size;       // subtract from stream send window
stream->queued++;                        // increment queued frame count
// src/http/v2/ngx_http_v2_filter_module.c — 1239~1244 (ngx_http_v2_send_chain)
ngx_http_v2_queue_frame(h2c, frame);     // enqueue DATA frame to output queue
h2c->send_window -= frame_size;          // subtract from connection send window
stream->send_window -= frame_size;       // subtract from stream send window
stream->queued++;                        // increment queued frame count

그러나 DATA가 큐에 들어갔다고 해서 곧바로 전송되는 것은 아니다. nginx의 출력 큐에서 frame이 전송되는 순서는 삽입 함수에 의해 결정된다. PING ACK나 SETTINGS ACK 같은 제어 frame은 ngx_http_v2_queue_blocked_frame()으로 큐의 앞쪽에 삽입되고, DATA frame은 ngx_http_v2_queue_frame()으로 stream 우선순위에 따라 뒤쪽에 배치된다.

// src/http/v2/ngx_http_v2.h — 286~301
// Control frame insertion: placed before blocked or stream-less frames (= front)
static ngx_inline void
ngx_http_v2_queue_blocked_frame(ngx_http_v2_connection_t *h2c,
    ngx_http_v2_out_frame_t *frame)
{
    ngx_http_v2_out_frame_t  **out;

    for (out = &h2c->last_out; *out; out = &(*out)->next) {
        if ((*out)->blocked || (*out)->stream == NULL) {
            break;
        }
    }

    frame->next = *out;
    *out = frame;
}
// src/http/v2/ngx_http_v2.h — 286~301
// Control frame insertion: placed before blocked or stream-less frames (= front)
static ngx_inline void
ngx_http_v2_queue_blocked_frame(ngx_http_v2_connection_t *h2c,
    ngx_http_v2_out_frame_t *frame)
{
    ngx_http_v2_out_frame_t  **out;

    for (out = &h2c->last_out; *out; out = &(*out)->next) {
        if ((*out)->blocked || (*out)->stream == NULL) {
            break;
        }
    }

    frame->next = *out;
    *out = frame;
}
// src/http/v2/ngx_http_v2.h — 286~301
// Control frame insertion: placed before blocked or stream-less frames (= front)
static ngx_inline void
ngx_http_v2_queue_blocked_frame(ngx_http_v2_connection_t *h2c,
    ngx_http_v2_out_frame_t *frame)
{
    ngx_http_v2_out_frame_t  **out;

    for (out = &h2c->last_out; *out; out = &(*out)->next) {
        if ((*out)->blocked || (*out)->stream == NULL) {
            break;
        }
    }

    frame->next = *out;
    *out = frame;
}
// src/http/v2/ngx_http_v2.h — 264~283
// DATA frame insertion: placed toward the back by stream priority
static ngx_inline void
ngx_http_v2_queue_frame(ngx_http_v2_connection_t *h2c,
    ngx_http_v2_out_frame_t *frame)
{
    ngx_http_v2_out_frame_t  **out;

    for (out = &h2c->last_out; *out; out = &(*out)->next) {
        if ((*out)->blocked || (*out)->stream == NULL) {
            break;
        }
        if (ngx_http_v2_stream_precedes((*out)->stream, frame->stream)) {
            break;
        }
    }

    frame->next = *out;
    *out = frame;
}
// src/http/v2/ngx_http_v2.h — 264~283
// DATA frame insertion: placed toward the back by stream priority
static ngx_inline void
ngx_http_v2_queue_frame(ngx_http_v2_connection_t *h2c,
    ngx_http_v2_out_frame_t *frame)
{
    ngx_http_v2_out_frame_t  **out;

    for (out = &h2c->last_out; *out; out = &(*out)->next) {
        if ((*out)->blocked || (*out)->stream == NULL) {
            break;
        }
        if (ngx_http_v2_stream_precedes((*out)->stream, frame->stream)) {
            break;
        }
    }

    frame->next = *out;
    *out = frame;
}
// src/http/v2/ngx_http_v2.h — 264~283
// DATA frame insertion: placed toward the back by stream priority
static ngx_inline void
ngx_http_v2_queue_frame(ngx_http_v2_connection_t *h2c,
    ngx_http_v2_out_frame_t *frame)
{
    ngx_http_v2_out_frame_t  **out;

    for (out = &h2c->last_out; *out; out = &(*out)->next) {
        if ((*out)->blocked || (*out)->stream == NULL) {
            break;
        }
        if (ngx_http_v2_stream_precedes((*out)->stream, frame->stream)) {
            break;
        }
    }

    frame->next = *out;
    *out = frame;
}

공격자는 이 차이를 이용한다. DATA를 큐에 넣게 한 직후 PING을 대량으로 보낸다. nginx는 PING마다 ACK 응답 frame을 만들어 ngx_http_v2_queue_blocked_frame()으로 큐 앞쪽에 삽입한다.

// src/http/v2/ngx_http_v2.c — 2414~2425 (ngx_http_v2_state_ping)
frame = ngx_http_v2_get_frame(h2c, NGX_HTTP_V2_PING_SIZE,
                              NGX_HTTP_V2_PING_FRAME,
                              NGX_HTTP_V2_ACK_FLAG, 0);
/* ... */
ngx_http_v2_queue_blocked_frame(h2c, frame);   // insert at front of queue
// src/http/v2/ngx_http_v2.c — 2414~2425 (ngx_http_v2_state_ping)
frame = ngx_http_v2_get_frame(h2c, NGX_HTTP_V2_PING_SIZE,
                              NGX_HTTP_V2_PING_FRAME,
                              NGX_HTTP_V2_ACK_FLAG, 0);
/* ... */
ngx_http_v2_queue_blocked_frame(h2c, frame);   // insert at front of queue
// src/http/v2/ngx_http_v2.c — 2414~2425 (ngx_http_v2_state_ping)
frame = ngx_http_v2_get_frame(h2c, NGX_HTTP_V2_PING_SIZE,
                              NGX_HTTP_V2_PING_FRAME,
                              NGX_HTTP_V2_ACK_FLAG, 0);
/* ... */
ngx_http_v2_queue_blocked_frame(h2c, frame);   // insert at front of queue

동시에 공격자는 TLS 연결에서 응답 읽기를 중단한다. 그러면 PING ACK가 큐 앞쪽에서 TCP/TLS 송신 버퍼를 가득 채우고, 뒤쪽에 있는 DATA frame에는 전송 순서가 돌아오지 않는다. DATA는 connection send window에서 이미 차감된 상태로 큐에 대기하게 된다.

이 상태가 익스플로잇의 핵심 조건이다. connection send window에서 빠져나간 양이, 아직 실제로 전송되지 않은 채 큐에 남아 있는 것이다. 공격자는 이 양을 두 가지 경로로 돌려받을 수 있다. 하나는 Stream ID 0 WINDOW_UPDATE(정상 경로)이고, 다른 하나는 RST_STREAM에 의한 cleanup(반환 경로)이다.

공격자는 먼저 Stream ID 0 WINDOW_UPDATE로 connection send window를 NGX_HTTP_V2_MAX_WINDOW(2^31−1)까지 채운다. 이것은 정상적인 프로토콜 동작이므로 nginx의 상한 검사를 통과한다. 곧이어 RST_STREAM으로 stream을 취소하면 ngx_http_v2_filter_cleanup()이 호출된다. 이 함수는 큐에 남은 해당 stream의 미전송 DATA frame을 제거하면서, 각 frame의 길이를 h2c->send_window에 되돌린다.

// src/http/v2/ngx_http_v2_filter_module.c — 1700~1768
static void
ngx_http_v2_filter_cleanup(void *data)
{
    ngx_http_v2_stream_t *stream = data;
    size_t  window;
    /* ... */

    window = 0;
    h2c = stream->connection;

    // walk the output queue, removing frames belonging to this stream
    for ( ;; ) {
        frame = *fn;
        if (frame == NULL) break;

        if (frame->stream == stream && !frame->blocked) {
            *fn = frame->next;             // unlink from queue
            window += frame->length;       // accumulate refund amount
            if (--stream->queued == 0) break;
            continue;
        }
        fn = &frame->next;
    }
    /* ... */

    h2c->send_window += window;            // ← no check against maximum
}
// src/http/v2/ngx_http_v2_filter_module.c — 1700~1768
static void
ngx_http_v2_filter_cleanup(void *data)
{
    ngx_http_v2_stream_t *stream = data;
    size_t  window;
    /* ... */

    window = 0;
    h2c = stream->connection;

    // walk the output queue, removing frames belonging to this stream
    for ( ;; ) {
        frame = *fn;
        if (frame == NULL) break;

        if (frame->stream == stream && !frame->blocked) {
            *fn = frame->next;             // unlink from queue
            window += frame->length;       // accumulate refund amount
            if (--stream->queued == 0) break;
            continue;
        }
        fn = &frame->next;
    }
    /* ... */

    h2c->send_window += window;            // ← no check against maximum
}
// src/http/v2/ngx_http_v2_filter_module.c — 1700~1768
static void
ngx_http_v2_filter_cleanup(void *data)
{
    ngx_http_v2_stream_t *stream = data;
    size_t  window;
    /* ... */

    window = 0;
    h2c = stream->connection;

    // walk the output queue, removing frames belonging to this stream
    for ( ;; ) {
        frame = *fn;
        if (frame == NULL) break;

        if (frame->stream == stream && !frame->blocked) {
            *fn = frame->next;             // unlink from queue
            window += frame->length;       // accumulate refund amount
            if (--stream->queued == 0) break;
            continue;
        }
        fn = &frame->next;
    }
    /* ... */

    h2c->send_window += window;            // ← no check against maximum
}

WINDOW_UPDATE로 이미 NGX_HTTP_V2_MAX_WINDOW까지 채워진 send_window에 cleanup이 미전송 DATA 길이를 한 번 더 더한다. 이 마지막 줄에는 더한 결과가 NGX_HTTP_V2_MAX_WINDOW를 넘는지 확인하는 코드가 없다. h2c->send_window는 size_t(부호 없는 64비트)이므로 2^31−1을 넘어도 overflow가 발생하지 않고, 값은 그대로 31비트 상한 너머로 올라간다.

send_window 변화:
  2^31−1 (규격상 최댓값)
  → DATA 큐 등록으로 미전송 DATA 길이만큼 차감
  → Stream ID 0 WINDOW_UPDATE로 같은 길이만큼 복구 (규격상 최댓값으로 돌아옴)
  → RST_STREAM → cleanup()에서 같은 길이를 한 번 더 반환 → 규격상 최댓값 초과
send_window 변화:
  2^31−1 (규격상 최댓값)
  → DATA 큐 등록으로 미전송 DATA 길이만큼 차감
  → Stream ID 0 WINDOW_UPDATE로 같은 길이만큼 복구 (규격상 최댓값으로 돌아옴)
  → RST_STREAM → cleanup()에서 같은 길이를 한 번 더 반환 → 규격상 최댓값 초과
send_window 변화:
  2^31−1 (규격상 최댓값)
  → DATA 큐 등록으로 미전송 DATA 길이만큼 차감
  → Stream ID 0 WINDOW_UPDATE로 같은 길이만큼 복구 (규격상 최댓값으로 돌아옴)
  → RST_STREAM → cleanup()에서 같은 길이를 한 번 더 반환 → 규격상 최댓값 초과

connection send window가 규격상 최댓값을 넘었으니, 이후 WINDOW_UPDATE가 거부되어야 한다. ngx_http_v2_state_window_update() 함수에는 실제로 상한 검사가 존재한다.

// src/http/v2/ngx_http_v2.c — 2564~2575
if (window > NGX_HTTP_V2_MAX_WINDOW - h2c->send_window) {   // bounds check
    return ngx_http_v2_connection_error(h2c, NGX_HTTP_V2_FLOW_CTRL_ERROR);
}
h2c->send_window += window;
// src/http/v2/ngx_http_v2.c — 2564~2575
if (window > NGX_HTTP_V2_MAX_WINDOW - h2c->send_window) {   // bounds check
    return ngx_http_v2_connection_error(h2c, NGX_HTTP_V2_FLOW_CTRL_ERROR);
}
h2c->send_window += window;
// src/http/v2/ngx_http_v2.c — 2564~2575
if (window > NGX_HTTP_V2_MAX_WINDOW - h2c->send_window) {   // bounds check
    return ngx_http_v2_connection_error(h2c, NGX_HTTP_V2_FLOW_CTRL_ERROR);
}
h2c->send_window += window;

이 검사는 "남은 공간 = MAX_WINDOW − 현재값"을 구하고, 증가량이 그 안에 들어가는지 확인한다. h2c->send_window가 MAX_WINDOW 이하일 때는 정확히 작동한다. 그러나 send_window가 이미 MAX_WINDOW보다 크면, MAX_WINDOW − send_window는 size_t 연산에서 음수가 되지 않고 2^64에 가까운 거대한 양수가 된다. 어떤 증가량이든 그보다 작으므로 검사를 항상 통과한다. SPDY 시절에는 더한 뒤 결과를 확인하는 방식이었으나, HTTP/2 구현에서 더하기 전에 남은 공간을 계산하는 방식으로 바뀌면서, "현재 값이 정상 범위"라는 전제가 코드에 묵시적으로 내장되었다. cleanup()의 무검사 반환이 그 전제를 깨뜨린 것이다.

상한 검사가 무력화되면 공격자는 WINDOW_UPDATE를 반복 전송하여 h2c->send_window를 64비트 최대치에 가깝게, 즉 2^64에서 공격자가 선택한 작은 양수를 뺀 값으로 올린다. h2c->send_window의 타입이 size_t이므로 이 값 자체는 정상적으로 저장된다. 문제는 nginx가 이 값을 사용할 때 발생한다.

nginx가 새 DATA frame을 전송하려 할 때, ngx_http_v2_send_chain() 함수는 h2c->send_window를 off_t(부호 있는 64비트)로 캐스팅하여 전송 가능 길이 limit과 비교한다.

// src/http/v2/ngx_http_v2_filter_module.c — 1144~1146
// limit: off_t (signed 64-bit)
// h2c->send_window: size_t (unsigned 64-bit), current value = 2^64 − d
if (limit == 0 || limit > (off_t) h2c->send_window) {
    limit = h2c->send_window;              // limit receives 2^64 − d
}
// src/http/v2/ngx_http_v2_filter_module.c — 1144~1146
// limit: off_t (signed 64-bit)
// h2c->send_window: size_t (unsigned 64-bit), current value = 2^64 − d
if (limit == 0 || limit > (off_t) h2c->send_window) {
    limit = h2c->send_window;              // limit receives 2^64 − d
}
// src/http/v2/ngx_http_v2_filter_module.c — 1144~1146
// limit: off_t (signed 64-bit)
// h2c->send_window: size_t (unsigned 64-bit), current value = 2^64 − d
if (limit == 0 || limit > (off_t) h2c->send_window) {
    limit = h2c->send_window;              // limit receives 2^64 − d
}

size_t로 "2^64에서 작은 양수를 뺀 값"은 off_t로 재해석하면 "작은 음수"가 된다. 양수인 limit은 음수보다 크므로 조건이 참이 되고, limit에 원래의 거대한 size_t 값이 대입된다. limit은 off_t이므로 이 시점부터 비트 패턴은 같지만 부호 해석이 뒤집혀 있다. 같은 함수 아래에서 이 limit이 frame_size로 전달된다.

// src/http/v2/ngx_http_v2_filter_module.c — 1163~1166
// frame_size: size_t (unsigned), a normal positive frame size
if ((off_t) frame_size > limit) {          // positive > negative → true
    frame_size = (size_t) limit;           // negative cast to size_t → huge positive
}
// src/http/v2/ngx_http_v2_filter_module.c — 1163~1166
// frame_size: size_t (unsigned), a normal positive frame size
if ((off_t) frame_size > limit) {          // positive > negative → true
    frame_size = (size_t) limit;           // negative cast to size_t → huge positive
}
// src/http/v2/ngx_http_v2_filter_module.c — 1163~1166
// frame_size: size_t (unsigned), a normal positive frame size
if ((off_t) frame_size > limit) {          // positive > negative → true
    frame_size = (size_t) limit;           // negative cast to size_t → huge positive
}

양수인 frame_size를 off_t로 변환하면 여전히 양수이고, limit은 음수이므로 조건이 참이다. limit을 다시 size_t로 변환하면 64비트 최대치에 가까운 거대한 양수로 돌아온다. 이 값은 rest 변수에 저장되어 ngx_http_v2_filter_get_shadow() 함수에 전달되고, 이 함수는 버퍼의 시작(pos)과 끝(last)을 설정한다.

// src/http/v2/ngx_http_v2_filter_module.c — 1288~1309
static ngx_chain_t *
ngx_http_v2_filter_get_shadow(ngx_http_v2_stream_t *stream,
    ngx_buf_t *buf, off_t offset, off_t size)
                                           // size param is off_t → huge positive reinterpreted as negative
{
    /* ... */
    if (ngx_buf_in_memory(chunk)) {
        chunk->pos += offset;              // buffer start position
        chunk->last = chunk->pos + size;   // negative size → last placed before pos
    }
    return cl;
}
// src/http/v2/ngx_http_v2_filter_module.c — 1288~1309
static ngx_chain_t *
ngx_http_v2_filter_get_shadow(ngx_http_v2_stream_t *stream,
    ngx_buf_t *buf, off_t offset, off_t size)
                                           // size param is off_t → huge positive reinterpreted as negative
{
    /* ... */
    if (ngx_buf_in_memory(chunk)) {
        chunk->pos += offset;              // buffer start position
        chunk->last = chunk->pos + size;   // negative size → last placed before pos
    }
    return cl;
}
// src/http/v2/ngx_http_v2_filter_module.c — 1288~1309
static ngx_chain_t *
ngx_http_v2_filter_get_shadow(ngx_http_v2_stream_t *stream,
    ngx_buf_t *buf, off_t offset, off_t size)
                                           // size param is off_t → huge positive reinterpreted as negative
{
    /* ... */
    if (ngx_buf_in_memory(chunk)) {
        chunk->pos += offset;              // buffer start position
        chunk->last = chunk->pos + size;   // negative size → last placed before pos
    }
    return cl;
}

정상적이라면 last는 pos 이후여야 하지만, 음수 size가 더해져 last가 pos보다 앞에 놓인다. 이 뒤집힌 버퍼가 TLS 출력 경로에 도달하면 ngx_ssl_send_chain()이 복사 길이를 last - pos로 계산한다.

// src/event/ngx_event_openssl.c — 3054~3150 (ngx_ssl_send_chain)
ssize_t size;                              // signed integer

size = in->buf->last - in->buf->pos;      // last before pos → negative

/* ... */

ngx_memcpy(buf->last, in->buf->pos, size);
// third argument of memcpy is size_t → negative becomes huge positive
// src/event/ngx_event_openssl.c — 3054~3150 (ngx_ssl_send_chain)
ssize_t size;                              // signed integer

size = in->buf->last - in->buf->pos;      // last before pos → negative

/* ... */

ngx_memcpy(buf->last, in->buf->pos, size);
// third argument of memcpy is size_t → negative becomes huge positive
// src/event/ngx_event_openssl.c — 3054~3150 (ngx_ssl_send_chain)
ssize_t size;                              // signed integer

size = in->buf->last - in->buf->pos;      // last before pos → negative

/* ... */

ngx_memcpy(buf->last, in->buf->pos, size);
// third argument of memcpy is size_t → negative becomes huge positive

memcpy()의 길이 인자는 size_t이므로, 작은 음수가 64비트 최대치에 가까운 거대한 양수로 변환된다. 보통이라면 프로세스가 즉시 비정상 종료되지만, glibc 2.24(2016년) 이후 x86-64의 memcpy 구현은 최적화를 위해 복사를 세 구간으로 처리한다. 아래는 AVX2 경로 기준이며, glibc 버전과 CPU의 SIMD 지원 범위(AVX-512 등)에 따라 복사 단위와 바이트 수가 달라진다. 처음 128바이트(head)와 끝 32바이트(tail)를 먼저 읽은 뒤, 가운데를 128바이트씩 반복문으로 복사하고, 마지막에 head와 tail을 쓴다. 반복문 커서는 복사 끝 주소에서 dest 쪽으로 감소하는데, 거대한 size를 더한 복사 끝 주소 (dest + size) mod 2^64은 주소 공간이 순환하여 dest보다 앞에 오게 된다. 반복문 진입 조건(cursor > dest)이 즉시 불충족되어 가운데 구간이 통째로 건너뛰어지고, glibc는 처음 128바이트와 끝 160바이트(128 + 32)만 복사한다.

실제 복사되는 영역 (size ≈ 2^64):

  src → src+127                 dest → dest+127
    [처음 128바이트 복사]           [처음 128바이트 복사]

  (가운데: 건너뜀)               (가운데: 건너뜀)

  복사 끝−160 → 복사 끝−1       복사 끝−160 → 복사 끝−1
    [끝 160바이트 복사]             [끝 160바이트 복사]
실제 복사되는 영역 (size ≈ 2^64):

  src → src+127                 dest → dest+127
    [처음 128바이트 복사]           [처음 128바이트 복사]

  (가운데: 건너뜀)               (가운데: 건너뜀)

  복사 끝−160 → 복사 끝−1       복사 끝−160 → 복사 끝−1
    [끝 160바이트 복사]             [끝 160바이트 복사]
실제 복사되는 영역 (size ≈ 2^64):

  src → src+127                 dest → dest+127
    [처음 128바이트 복사]           [처음 128바이트 복사]

  (가운데: 건너뜀)               (가운데: 건너뜀)

  복사 끝−160 → 복사 끝−1       복사 끝−160 → 복사 끝−1
    [끝 160바이트 복사]             [끝 160바이트 복사]

공격자가 send_window의 값을 조절하면 "복사 끝" 주소의 위치를 바이트 단위로 제어할 수 있다. 여기서 공격자는 복사의 dest와 src 양쪽을 제어해야 한다.

dest는 TLS 평문 버퍼에서 다음 응답 데이터를 쓸 위치이며, 그 앞에 쌓인 제어 frame의 크기로 결정된다. nginx 코드에서 PING ACK는 17바이트(frame header 9 + 본문 8), SETTINGS ACK는 9바이트(frame header 9 + 본문 0)다.

// src/http/v2/ngx_http_v2.h — 26
#define NGX_HTTP_V2_FRAME_HEADER_SIZE   9  // all HTTP/2 frame headers are 9 bytes

// src/http/v2/ngx_http_v2.c — 30~34
#define NGX_HTTP_V2_SETTINGS_ACK_SIZE   0  // SETTINGS ACK has no body
#define NGX_HTTP_V2_PING_SIZE           8  // PING body is 8 bytes
// src/http/v2/ngx_http_v2.h — 26
#define NGX_HTTP_V2_FRAME_HEADER_SIZE   9  // all HTTP/2 frame headers are 9 bytes

// src/http/v2/ngx_http_v2.c — 30~34
#define NGX_HTTP_V2_SETTINGS_ACK_SIZE   0  // SETTINGS ACK has no body
#define NGX_HTTP_V2_PING_SIZE           8  // PING body is 8 bytes
// src/http/v2/ngx_http_v2.h — 26
#define NGX_HTTP_V2_FRAME_HEADER_SIZE   9  // all HTTP/2 frame headers are 9 bytes

// src/http/v2/ngx_http_v2.c — 30~34
#define NGX_HTTP_V2_SETTINGS_ACK_SIZE   0  // SETTINGS ACK has no body
#define NGX_HTTP_V2_PING_SIZE           8  // PING body is 8 bytes

공격자가 보낸 PING과 SETTINGS의 개수에 따라 TLS 버퍼 안에서 DATA 본문이 시작되는 위치가 결정되므로, dest는 공격자가 선택한 값이 된다.

src는 nginx가 TLS 버퍼로 옮기려는 응답 데이터의 시작 위치다. 공격자는 Range 헤더에 여러 범위를 지정하여 nginx가 multipart 응답을 생성하게 만든다. nginx는 경계 문자열(boundary)을 요청 메모리 풀에 할당하고 그 주소를 응답 버퍼의 시작으로 사용한다.

// src/http/modules/ngx_http_range_filter_module.c — 504
ctx->boundary_header.data = ngx_pnalloc(r->pool, size);  // allocate boundary string in pool

// same file — 880~881
b->pos = ctx->boundary_header.data;        // this address becomes memcpy src
b->last = ctx->boundary_header.data + ctx->boundary_header.len;
// src/http/modules/ngx_http_range_filter_module.c — 504
ctx->boundary_header.data = ngx_pnalloc(r->pool, size);  // allocate boundary string in pool

// same file — 880~881
b->pos = ctx->boundary_header.data;        // this address becomes memcpy src
b->last = ctx->boundary_header.data + ctx->boundary_header.len;
// src/http/modules/ngx_http_range_filter_module.c — 504
ctx->boundary_header.data = ngx_pnalloc(r->pool, size);  // allocate boundary string in pool

// same file — 880~881
b->pos = ctx->boundary_header.data;        // this address becomes memcpy src
b->last = ctx->boundary_header.data + ctx->boundary_header.len;

src 근처의 메모리 내용도 공격자가 제어할 수 있다. Cookie 헤더를 여러 개 보내면 ngx_http_v2_construct_cookie_header() 함수가 모든 값을 하나의 버퍼로 합쳐 같은 풀에 할당하고, 헤더 구조체에 nginx 바이너리의 고정 주소(h->key.data = cookie.data)와 힙 주소(h->value.data = buf)를 함께 저장한다.

// src/http/v2/ngx_http_v2.c — 3728~3768
do {
    len += vals[i].len + 2;                // each cookie value length + "; " separator
} while (++i != cookies->nelts);
len -= 2;                                  // remove trailing separator

buf = ngx_pnalloc(r->pool, len + 1);      // allocate cookie buffer in pool
/* ... */
h->key.data = cookie.data;                 // "cookie" string → fixed address in nginx binary
h->value.len = len;                        // attacker-controllable length
h->value.data = buf;                       // pool-allocated buffer → heap address
// src/http/v2/ngx_http_v2.c — 3728~3768
do {
    len += vals[i].len + 2;                // each cookie value length + "; " separator
} while (++i != cookies->nelts);
len -= 2;                                  // remove trailing separator

buf = ngx_pnalloc(r->pool, len + 1);      // allocate cookie buffer in pool
/* ... */
h->key.data = cookie.data;                 // "cookie" string → fixed address in nginx binary
h->value.len = len;                        // attacker-controllable length
h->value.data = buf;                       // pool-allocated buffer → heap address
// src/http/v2/ngx_http_v2.c — 3728~3768
do {
    len += vals[i].len + 2;                // each cookie value length + "; " separator
} while (++i != cookies->nelts);
len -= 2;                                  // remove trailing separator

buf = ngx_pnalloc(r->pool, len + 1);      // allocate cookie buffer in pool
/* ... */
h->key.data = cookie.data;                 // "cookie" string → fixed address in nginx binary
h->value.len = len;                        // attacker-controllable length
h->value.data = buf;                       // pool-allocated buffer → heap address

nginx의 풀 할당기(ngx_palloc_small)는 작은 객체를 현재 풀 블록의 마지막 할당 위치 바로 뒤에 연속으로 배치하므로, Cookie·Range·URI의 크기를 조절하면 경계 문자열(src), Cookie 버퍼, 헤더 구조체의 풀 블록 내 상대 위치를 맞출 수 있다.

// src/core/ngx_palloc.c — 148~166 (ngx_palloc_small)
m = p->d.last;                             // current allocation cursor

if ((size_t) (p->d.end - m) >= size) {
    p->d.last = m + size;                  // advance cursor for next allocation
    return m;                              // return address right after previous allocation
}
// src/core/ngx_palloc.c — 148~166 (ngx_palloc_small)
m = p->d.last;                             // current allocation cursor

if ((size_t) (p->d.end - m) >= size) {
    p->d.last = m + size;                  // advance cursor for next allocation
    return m;                              // return address right after previous allocation
}
// src/core/ngx_palloc.c — 148~166 (ngx_palloc_small)
m = p->d.last;                             // current allocation cursor

if ((size_t) (p->d.end - m) >= size) {
    p->d.last = m + size;                  // advance cursor for next allocation
    return m;                              // return address right after previous allocation
}

이 모든 조건이 맞춰진 상태에서 비정상 memcpy가 실행되면, glibc의 "끝" 복사 160바이트가 공격자가 준비한 두 가지 역할을 동시에 수행한다. 앞쪽 96바이트는 TLS 평문 버퍼 앞의 힙 메타데이터를 덮어쓰고(out-of-bounds write), 뒤쪽 64바이트는 Cookie 헤더 구조체에 담긴 nginx 바이너리 주소와 힙 주소를 TLS 평문 버퍼의 첫 64바이트에 복사하여 client에게 응답으로 전송한다(정보 노출). 한 번의 비정상 복사로 out-of-bounds write와 address leak이 동시에 성립한다.

공격자는 TLS 응답에서 읽어낸 주소를 이용해 요청 cleanup 구조체의 함수 포인터를 덮어쓴다. nginx가 요청 처리를 마치고 cleanup handler를 호출하면 공격자가 지정한 주소로 실행 흐름이 이동하고, worker 프로세스 권한으로 임의 명령이 실행된다.

4. HTTP/2 연결 슬롯 정리 use-after-free(CVE-2026-123633) 상세 분석

이 취약점은 2.3절에서 설명한 nginx의 연결 슬롯 관리와 HTTP/2 연결의 상태 전이가 맞물려 발생한다.

HTTP/2 연결이 유휴 상태(활성 stream 없음, 전송 대기 frame 없음)가 되면, ngx_http_v2_handle_connection() 함수가 연결을 reusable 큐에 등록하고 read handler를 ngx_http_v2_idle_handler로 교체한다. idle handler는 새 데이터가 도착했을 때 연결을 reusable 큐에서 제거하는 코드를 포함한다.

// src/http/v2/ngx_http_v2.c — 4937 (inside ngx_http_v2_idle_handler)
ngx_reusable_connection(c, 0);    // remove from queue and resume request processing
// src/http/v2/ngx_http_v2.c — 4937 (inside ngx_http_v2_idle_handler)
ngx_reusable_connection(c, 0);    // remove from queue and resume request processing
// src/http/v2/ngx_http_v2.c — 4937 (inside ngx_http_v2_idle_handler)
ngx_reusable_connection(c, 0);    // remove from queue and resume request processing

이 교체가 정상적으로 이루어지면, 새 stream이 열릴 때 idle handler가 연결을 큐에서 제거하므로 drain의 대상에서 빠진다. 그러나 교체가 일어나지 않고 기존의 ngx_http_v2_read_handler가 남으면, 이 핸들러에는 큐 제거 코드가 없어 연결이 큐에 그대로 남게 된다.

문제는 ngx_http_v2_handle_connection() 안에서 reusable 등록과 incomplete 검사의 순서에 있다.

// src/http/v2/ngx_http_v2.c — 628~674
if (h2c->last_out || h2c->processing) {    // return if active streams or pending frames
    return;
}
/* ... */

ngx_reusable_connection(c, 1);             // ① register in reusable queue

if (h2c->state.incomplete) {               // ② check incomplete AFTER registration
    return;                                // ← returns here if incomplete
}

// ③ code below only reached when NOT incomplete
ngx_destroy_pool(h2c->pool);
/* ... replace read handler with ngx_http_v2_idle_handler ... */
// src/http/v2/ngx_http_v2.c — 628~674
if (h2c->last_out || h2c->processing) {    // return if active streams or pending frames
    return;
}
/* ... */

ngx_reusable_connection(c, 1);             // ① register in reusable queue

if (h2c->state.incomplete) {               // ② check incomplete AFTER registration
    return;                                // ← returns here if incomplete
}

// ③ code below only reached when NOT incomplete
ngx_destroy_pool(h2c->pool);
/* ... replace read handler with ngx_http_v2_idle_handler ... */
// src/http/v2/ngx_http_v2.c — 628~674
if (h2c->last_out || h2c->processing) {    // return if active streams or pending frames
    return;
}
/* ... */

ngx_reusable_connection(c, 1);             // ① register in reusable queue

if (h2c->state.incomplete) {               // ② check incomplete AFTER registration
    return;                                // ← returns here if incomplete
}

// ③ code below only reached when NOT incomplete
ngx_destroy_pool(h2c->pool);
/* ... replace read handler with ngx_http_v2_idle_handler ... */

①에서 먼저 reusable 큐에 등록한 뒤 ②에서 incomplete를 검사한다. incomplete 상태이면 ③의 idle handler 교체에 도달하지 못하고 반환되므로, read handler가 기존의 ngx_http_v2_read_handler로 남는다. idle handler에는 연결을 reusable 큐에서 제거하는 코드가 있지만, read handler에는 그런 코드가 없다.

공격자가 HEADERS frame을 TCP 세그먼트 경계에 맞춰 나누어 보내면, nginx가 앞부분만 수신한 시점에서 h2c->state.incomplete가 1이 된다. ngx_http_v2_handle_connection()이 호출되면 연결이 reusable 큐에 등록되지만 idle handler로 교체되지 않는다. 이후 나머지를 수신하여 stream을 열고 요청 처리를 시작하더라도, 연결은 reusable 큐에 그대로 남아 drain의 대상이 된다.

이 연결의 요청을 proxy_pass로 백엔드에 전달하려면 업스트림 연결을 위한 새 슬롯이 필요하다. ngx_event_connect_peer()가 ngx_get_connection()을 호출했을 때 여유 슬롯이 부족하면 drain이 실행되고, 현재 요청이 속한 HTTP/2 연결이 reusable 큐에 있으므로 정리 대상으로 선택될 수 있다. drain이 호출한 HTTP/2 read handler는 c->close 플래그를 확인하고 GOAWAY 전송을 시도한다.

// src/http/v2/ngx_http_v2.c — 356~382
if (c->close) {
    c->close = 0;
    /* ... */
    if (!h2c->goaway) {
        h2c->goaway = 1;

        if (ngx_http_v2_send_goaway(h2c, NGX_HTTP_V2_NO_ERROR) == NGX_ERROR)
        {
            ngx_http_v2_finalize_connection(h2c, 0);   // enters here on TCP reset
            return;
        }

        if (ngx_http_v2_send_output_queue(h2c) == NGX_ERROR) {
            ngx_http_v2_finalize_connection(h2c, 0);
            return;
        }
    }
}
// src/http/v2/ngx_http_v2.c — 356~382
if (c->close) {
    c->close = 0;
    /* ... */
    if (!h2c->goaway) {
        h2c->goaway = 1;

        if (ngx_http_v2_send_goaway(h2c, NGX_HTTP_V2_NO_ERROR) == NGX_ERROR)
        {
            ngx_http_v2_finalize_connection(h2c, 0);   // enters here on TCP reset
            return;
        }

        if (ngx_http_v2_send_output_queue(h2c) == NGX_ERROR) {
            ngx_http_v2_finalize_connection(h2c, 0);
            return;
        }
    }
}
// src/http/v2/ngx_http_v2.c — 356~382
if (c->close) {
    c->close = 0;
    /* ... */
    if (!h2c->goaway) {
        h2c->goaway = 1;

        if (ngx_http_v2_send_goaway(h2c, NGX_HTTP_V2_NO_ERROR) == NGX_ERROR)
        {
            ngx_http_v2_finalize_connection(h2c, 0);   // enters here on TCP reset
            return;
        }

        if (ngx_http_v2_send_output_queue(h2c) == NGX_ERROR) {
            ngx_http_v2_finalize_connection(h2c, 0);
            return;
        }
    }
}

client가 TCP reset을 보낸 상태라면 GOAWAY 전송이 실패하고, ngx_http_v2_finalize_connection()이 연결에 속한 모든 stream을 정리한다. 이 과정에서 ngx_http_free_request()가 요청 풀을 해제하므로 요청 구조체 r과 업스트림 구조체 u도 함께 해제된다.

drain이 끝나고 실행 흐름이 ngx_event_connect_peer()로 돌아오면, 이 함수는 인자로 받은 u->peer 포인터를 다시 참조한다. 그러나 u는 이미 해제되었으므로 해제된 메모리에 접근하게 되어 use-after-free가 발생한다.

5. QUIC 스트림 생성 중 use-after-free(CVE-2026-121810) 상세 분석

이 취약점은 nginx의 QUIC/HTTP/3 구현에서 stream 생성 과정의 타이밍 문제로 발생한다. 2.3절의 drain 메커니즘이 관련되지만, 연결이 reusable 큐에 잘못 남게 되는 경로가 다르다.

HTTP/3는 QUIC 프로토콜 위에서 동작한다. QUIC 연결 하나에서 여러 요청을 stream 단위로 처리하는데, nginx는 이를 위해 두 종류의 ngx_connection_t 객체를 사용한다. 하나는 QUIC 연결 전체를 대표하는 부모 연결이고, 나머지는 각 stream에 할당되는 자식 연결이다. 부모 연결과 자식 연결 모두 같은 워커의 연결 슬롯 풀에서 할당된다.

각 stream은 ngx_quic_stream_t 구조체로 관리되며, 부모 연결의 red-black tree(qc->streams.tree)에 등록된다.

// src/event/quic/ngx_event_quic.h — 105~127
struct ngx_quic_stream_s {
    ngx_rbtree_node_t              node;       // node inserted into the tree
    ngx_queue_t                    queue;
    ngx_connection_t              *parent;      // parent QUIC connection
    ngx_connection_t              *connection;   // connection slot for this stream
    uint64_t                       id;
    /* ... send/receive state fields ... */
    unsigned                       cancelable:1; // whether the stream is cancelable
    /* ... */
};
// src/event/quic/ngx_event_quic.h — 105~127
struct ngx_quic_stream_s {
    ngx_rbtree_node_t              node;       // node inserted into the tree
    ngx_queue_t                    queue;
    ngx_connection_t              *parent;      // parent QUIC connection
    ngx_connection_t              *connection;   // connection slot for this stream
    uint64_t                       id;
    /* ... send/receive state fields ... */
    unsigned                       cancelable:1; // whether the stream is cancelable
    /* ... */
};
// src/event/quic/ngx_event_quic.h — 105~127
struct ngx_quic_stream_s {
    ngx_rbtree_node_t              node;       // node inserted into the tree
    ngx_queue_t                    queue;
    ngx_connection_t              *parent;      // parent QUIC connection
    ngx_connection_t              *connection;   // connection slot for this stream
    uint64_t                       id;
    /* ... send/receive state fields ... */
    unsigned                       cancelable:1; // whether the stream is cancelable
    /* ... */
};

stream이 닫힐 때 nginx는 부모 연결도 함께 정리할 수 있는지 ngx_quic_can_shutdown() 함수로 검사한다. 이 함수는 부모의 stream 트리를 순회하면서, 취소 불가능한(cancelable == 0) stream이 하나라도 남아 있으면 NGX_DECLINED을 반환한다. 모든 stream이 취소 가능하거나 트리가 비어 있으면 NGX_OK를 반환하고, 부모 연결을 reusable 큐에 등록한다.

// src/event/quic/ngx_event_quic_streams.c — 1168~1170
if (!pc->reusable && ngx_quic_can_shutdown(pc) == NGX_OK) {
    ngx_reusable_connection(pc, 1);        // register parent in reusable queue
}
// src/event/quic/ngx_event_quic_streams.c — 1168~1170
if (!pc->reusable && ngx_quic_can_shutdown(pc) == NGX_OK) {
    ngx_reusable_connection(pc, 1);        // register parent in reusable queue
}
// src/event/quic/ngx_event_quic_streams.c — 1168~1170
if (!pc->reusable && ngx_quic_can_shutdown(pc) == NGX_OK) {
    ngx_reusable_connection(pc, 1);        // register parent in reusable queue
}

이 판단은 트리에 등록된 stream만을 대상으로 한다. 아직 트리에 등록되지 않은 stream은 검사 대상에서 빠진다.

새 stream을 만드는 ngx_quic_create_stream() 함수의 실행 순서가 문제의 핵심이다.

// src/event/quic/ngx_event_quic_streams.c — 734~814
reusable = c->reusable;
ngx_reusable_connection(c, 0);             // ① remove parent from reusable queue

sc = ngx_get_connection(c->fd, log);       // ② allocate connection slot (drain may fire here)
/* ... ~80 lines of initialization code ... */

ngx_rbtree_insert(&qc->streams.tree, &qs->node);  // ③ register new stream in tree (end of function)
// src/event/quic/ngx_event_quic_streams.c — 734~814
reusable = c->reusable;
ngx_reusable_connection(c, 0);             // ① remove parent from reusable queue

sc = ngx_get_connection(c->fd, log);       // ② allocate connection slot (drain may fire here)
/* ... ~80 lines of initialization code ... */

ngx_rbtree_insert(&qc->streams.tree, &qs->node);  // ③ register new stream in tree (end of function)
// src/event/quic/ngx_event_quic_streams.c — 734~814
reusable = c->reusable;
ngx_reusable_connection(c, 0);             // ① remove parent from reusable queue

sc = ngx_get_connection(c->fd, log);       // ② allocate connection slot (drain may fire here)
/* ... ~80 lines of initialization code ... */

ngx_rbtree_insert(&qc->streams.tree, &qs->node);  // ③ register new stream in tree (end of function)

함수 시작 부분에서 부모를 reusable 큐에서 제거하는 것은, ngx_get_connection() 내부에서 drain이 실행될 때 부모가 닫히는 것을 방지하기 위함이다. 그러나 트리 등록(ngx_rbtree_insert)은 함수의 거의 마지막에 위치하므로, ngx_get_connection() 호출 시점에 새 stream은 아직 트리에 존재하지 않는다.

이 상태에서 drain이 실행되어 같은 부모의 기존 유휴 stream이 닫히면, stream close 과정에서 ngx_quic_can_shutdown()이 부모의 stream 트리를 순회한다. 생성 중인 새 stream은 트리에 없고, 다른 취소 불가 stream도 없다면, 함수는 부모 연결을 종료해도 된다고 판단하여 reusable 큐에 다시 등록한다. 함수 시작에서 제거한 보호가 무효화되는 것이다.

새 stream 생성이 끝난 후에도 부모 연결은 reusable 큐에 남아 있다. 이 stream의 요청을 proxy_pass로 전달하기 위해 업스트림 연결을 시도하면, ngx_get_connection()에서 다시 drain이 실행되고, 이번에는 부모 QUIC 연결이 정리 대상으로 선택될 수 있다. 부모 연결이 닫히면 현재 stream의 요청 메모리도 해제되며, ngx_event_connect_peer()가 복귀 후 해제된 u->peer에 접근하면서 use-after-free가 발생한다. CVE-2026-123633과 같은 패턴이지만, 부모 연결이 reusable 큐에 잘못 남게 되는 원인이 incomplete frame이 아니라 트리 등록 전 타이밍이라는 점이 다르다.

6. DNS 리졸버 use-after-free(CVE-2026-123634) 상세 분석

이 취약점은 nginx 내장 리졸버, 변수 기반 proxy_pass, mirror 지시어 세 가지가 맞물려 발생한다.

nginx는 resolver 지시어로 지정한 DNS 서버를 사용해 도메인 이름을 직접 조회할 수 있다. 조회는 비동기로 수행되며, 조회 요청 하나당 리졸버 컨텍스트(ngx_resolver_ctx_t) 구조체가 하나 만들어진다. 이 구조체에는 현재 조회 상태(state), 결과를 받을 콜백(handler), 그리고 같은 도메인을 기다리는 다음 컨텍스트를 가리키는 포인터(next)가 들어 있다.

// src/core/ngx_resolver.h — 197~228
struct ngx_resolver_ctx_s {
    ngx_resolver_ctx_t       *next;        // next item in the same-domain waiting list
    ngx_resolver_t           *resolver;
    ngx_resolver_node_t      *node;        // resolver node this lookup belongs to
    /* ... */
    ngx_int_t                 state;       // NGX_AGAIN means still waiting for response
    ngx_str_t                 name;        // domain name being resolved
    /* ... */
    ngx_resolver_handler_pt   handler;     // callback invoked when DNS response arrives
    void                     *data;
    /* ... */
};
// src/core/ngx_resolver.h — 197~228
struct ngx_resolver_ctx_s {
    ngx_resolver_ctx_t       *next;        // next item in the same-domain waiting list
    ngx_resolver_t           *resolver;
    ngx_resolver_node_t      *node;        // resolver node this lookup belongs to
    /* ... */
    ngx_int_t                 state;       // NGX_AGAIN means still waiting for response
    ngx_str_t                 name;        // domain name being resolved
    /* ... */
    ngx_resolver_handler_pt   handler;     // callback invoked when DNS response arrives
    void                     *data;
    /* ... */
};
// src/core/ngx_resolver.h — 197~228
struct ngx_resolver_ctx_s {
    ngx_resolver_ctx_t       *next;        // next item in the same-domain waiting list
    ngx_resolver_t           *resolver;
    ngx_resolver_node_t      *node;        // resolver node this lookup belongs to
    /* ... */
    ngx_int_t                 state;       // NGX_AGAIN means still waiting for response
    ngx_str_t                 name;        // domain name being resolved
    /* ... */
    ngx_resolver_handler_pt   handler;     // callback invoked when DNS response arrives
    void                     *data;
    /* ... */
};

같은 도메인에 대한 조회 요청이 여러 개 들어오면, 첫 번째만 실제 DNS 질의를 보내고 나머지는 리졸버 노드(ngx_resolver_node_t)의 대기 목록(rn->waiting)에 연결 리스트로 추가된다. DNS 응답이 오면 이 목록을 순회하며 각 컨텍스트의 handler를 호출한다.

// src/core/ngx_resolver.h — 144 (inside ngx_resolver_node_t)
    ngx_resolver_ctx_t       *waiting;     // list of contexts waiting for this domain's DNS response
// src/core/ngx_resolver.h — 144 (inside ngx_resolver_node_t)
    ngx_resolver_ctx_t       *waiting;     // list of contexts waiting for this domain's DNS response
// src/core/ngx_resolver.h — 144 (inside ngx_resolver_node_t)
    ngx_resolver_ctx_t       *waiting;     // list of contexts waiting for this domain's DNS response

proxy_pass <http://$host처럼> 변수를 포함한 proxy_pass를 사용하면, 요청마다 호스트 이름이 달라질 수 있다. nginx는 요청이 들어올 때마다 변수를 평가하고, 결과 도메인을 resolver로 조회한다. 조회 결과가 올 때까지 요청은 대기 상태(NGX_AGAIN)로 남는다.

mirror 지시어를 사용하면 nginx는 메인 요청을 처리하면서 별도 location으로 백그라운드 서브리퀘스트를 보낸다. 서브리퀘스트는 ngx_http_subrequest() 함수로 생성되며, 메인 요청의 정리 작업(cleanup) 목록에 등록된다. 메인 요청이 종료되면 서브리퀘스트의 cleanup도 함께 실행된다.

// src/http/modules/ngx_http_mirror_module.c — 161~163
if (ngx_http_subrequest(r, &name[i], &r->args, &sr, NULL,
                        NGX_HTTP_SUBREQUEST_BACKGROUND)   // background subrequest
    != NGX_OK)
// src/http/modules/ngx_http_mirror_module.c — 161~163
if (ngx_http_subrequest(r, &name[i], &r->args, &sr, NULL,
                        NGX_HTTP_SUBREQUEST_BACKGROUND)   // background subrequest
    != NGX_OK)
// src/http/modules/ngx_http_mirror_module.c — 161~163
if (ngx_http_subrequest(r, &name[i], &r->args, &sr, NULL,
                        NGX_HTTP_SUBREQUEST_BACKGROUND)   // background subrequest
    != NGX_OK)

메인 요청과 미러 서브리퀘스트가 같은 도메인의 업스트림을 사용하면(같은 proxy_pass <http://$host> 경로를 거치면), 두 요청의 리졸버 컨텍스트가 같은 노드의 rn->waiting 목록에 들어간다. 이것이 취약점의 전제 조건이다.

DNS 응답이 도착하면 nginx는 대기 목록을 노드에서 분리하고, 로컬 변수 next에 옮긴 뒤 rn->waiting을 NULL로 비운다. 그리고 next를 따라가며 각 컨텍스트의 handler를 호출한다.

// src/core/ngx_resolver.c — 2131~2147
next = rn->waiting;        // copy waiting list to local variable
rn->waiting = NULL;        // clear the node's waiting list

/* ... */

while (next) {
    ctx = next;
    ctx->state = code;
    ctx->valid = ngx_time() + (r->valid ? r->valid : 10);
    next = ctx->next;      // save next context in advance

    ctx->handler(ctx);     // invoke completion handler for current context
}
// src/core/ngx_resolver.c — 2131~2147
next = rn->waiting;        // copy waiting list to local variable
rn->waiting = NULL;        // clear the node's waiting list

/* ... */

while (next) {
    ctx = next;
    ctx->state = code;
    ctx->valid = ngx_time() + (r->valid ? r->valid : 10);
    next = ctx->next;      // save next context in advance

    ctx->handler(ctx);     // invoke completion handler for current context
}
// src/core/ngx_resolver.c — 2131~2147
next = rn->waiting;        // copy waiting list to local variable
rn->waiting = NULL;        // clear the node's waiting list

/* ... */

while (next) {
    ctx = next;
    ctx->state = code;
    ctx->valid = ngx_time() + (r->valid ? r->valid : 10);
    next = ctx->next;      // save next context in advance

    ctx->handler(ctx);     // invoke completion handler for current context
}

메인 요청과 미러 서브리퀘스트의 컨텍스트가 같은 목록에 있을 때, DNS 조회가 실패하면 메인 요청의 handler(ngx_http_upstream_resolve_handler)가 먼저 호출된다. 이 핸들러는 client에 502 응답 전송을 시도하는데, client가 TCP reset을 보낸 상태라면 전송이 실패한다. 전송 실패는 ngx_http_terminate_request()를 거쳐 메인 요청의 전체 종료로 이어지고, 이 종료 과정에서 메인 요청에 등록된 모든 정리 작업(cleanup)이 실행된다. 미러 서브리퀘스트의 업스트림 정리 작업도 메인 요청에 등록되어 있으므로 함께 실행된다.

// src/http/ngx_http_upstream.c — 4802~4805
if (u->resolved && u->resolved->ctx) {
    ngx_resolve_name_done(u->resolved->ctx);   // attempt to release mirror context
    u->resolved->ctx = NULL;
}
// src/http/ngx_http_upstream.c — 4802~4805
if (u->resolved && u->resolved->ctx) {
    ngx_resolve_name_done(u->resolved->ctx);   // attempt to release mirror context
    u->resolved->ctx = NULL;
}
// src/http/ngx_http_upstream.c — 4802~4805
if (u->resolved && u->resolved->ctx) {
    ngx_resolve_name_done(u->resolved->ctx);   // attempt to release mirror context
    u->resolved->ctx = NULL;
}

ngx_resolve_name_done() 함수는 아직 응답을 받지 못한(NGX_AGAIN 상태의) 컨텍스트를 rn->waiting 목록에서 찾아 제거한 뒤 메모리를 해제하도록 되어 있다. 그러나 rn->waiting은 순회 시작 시 이미 NULL로 비워졌다.

// src/core/ngx_resolver.c — 554~595 (ngx_resolve_name_done)
if (ctx->state == NGX_AGAIN || ctx->state == NGX_RESOLVE_TIMEDOUT) {
    rn = ctx->node;

    if (rn) {
        p = &rn->waiting;      // rn->waiting is already NULL
        w = rn->waiting;       // w = NULL

        while (w) {            // loop body never entered
            /* ... */
        }

        ngx_log_error(NGX_LOG_ALERT, r->log, 0,
                      "could not cancel %V resolving", &ctx->name);
    }
}

done:
    /* ... */
    ngx_resolver_free_locked(r, ctx);      // frees memory despite not finding the context
// src/core/ngx_resolver.c — 554~595 (ngx_resolve_name_done)
if (ctx->state == NGX_AGAIN || ctx->state == NGX_RESOLVE_TIMEDOUT) {
    rn = ctx->node;

    if (rn) {
        p = &rn->waiting;      // rn->waiting is already NULL
        w = rn->waiting;       // w = NULL

        while (w) {            // loop body never entered
            /* ... */
        }

        ngx_log_error(NGX_LOG_ALERT, r->log, 0,
                      "could not cancel %V resolving", &ctx->name);
    }
}

done:
    /* ... */
    ngx_resolver_free_locked(r, ctx);      // frees memory despite not finding the context
// src/core/ngx_resolver.c — 554~595 (ngx_resolve_name_done)
if (ctx->state == NGX_AGAIN || ctx->state == NGX_RESOLVE_TIMEDOUT) {
    rn = ctx->node;

    if (rn) {
        p = &rn->waiting;      // rn->waiting is already NULL
        w = rn->waiting;       // w = NULL

        while (w) {            // loop body never entered
            /* ... */
        }

        ngx_log_error(NGX_LOG_ALERT, r->log, 0,
                      "could not cancel %V resolving", &ctx->name);
    }
}

done:
    /* ... */
    ngx_resolver_free_locked(r, ctx);      // frees memory despite not finding the context

함수는 대기 목록에서 컨텍스트를 찾지 못했음에도 done: 레이블로 이동하여 메모리를 해제한다. 미러 서브리퀘스트의 리졸버 컨텍스트는 이 시점에서 해제된다.

메인 요청의 handler 실행이 끝나면 리졸버의 while (next) 루프로 제어가 돌아온다. 루프는 미리 저장해둔 next 포인터를 따라 이미 해제된 미러 컨텍스트로 이동한다. 해제된 메모리에서 ctx->state와 ctx->valid를 쓰고, ctx->next를 읽은 뒤, ctx->handler(ctx)를 호출한다. 해제된 영역이 공격자가 제어하는 데이터로 재할당되면, handler 필드에 임의 주소를 넣어 명령 포인터를 제어할 수 있다.

7. 메일 프록시 인증 use-after-free(CVE-2026-113425) 상세 분석

이 취약점은 nginx 메일 프록시의 인증 흐름에서 발생한다.

nginx는 HTTP 서버로만 쓰이는 것이 아니다. mail 블록을 설정하면 IMAP, POP3, SMTP 프로토콜을 중계하는 메일 프록시로도 동작한다. 클라이언트가 메일 포트에 접속하면 nginx는 세션(ngx_mail_session_t) 구조체를 만들고, 클라이언트 연결의 메모리 풀에 할당한다.

// src/mail/ngx_mail.h — 191~247 (excerpt)
typedef struct {
    uint32_t                signature;         // "MAIL"
    ngx_connection_t       *connection;        // TCP connection to the client
    ngx_str_t               out;               // pending response to the client
    ngx_buf_t              *buffer;
    void                  **ctx;               // module context array
    /* ... */
    ngx_str_t               login;
    ngx_str_t               passwd;
    /* ... */
} ngx_mail_session_t;
// src/mail/ngx_mail.h — 191~247 (excerpt)
typedef struct {
    uint32_t                signature;         // "MAIL"
    ngx_connection_t       *connection;        // TCP connection to the client
    ngx_str_t               out;               // pending response to the client
    ngx_buf_t              *buffer;
    void                  **ctx;               // module context array
    /* ... */
    ngx_str_t               login;
    ngx_str_t               passwd;
    /* ... */
} ngx_mail_session_t;
// src/mail/ngx_mail.h — 191~247 (excerpt)
typedef struct {
    uint32_t                signature;         // "MAIL"
    ngx_connection_t       *connection;        // TCP connection to the client
    ngx_str_t               out;               // pending response to the client
    ngx_buf_t              *buffer;
    void                  **ctx;               // module context array
    /* ... */
    ngx_str_t               login;
    ngx_str_t               passwd;
    /* ... */
} ngx_mail_session_t;

세션 s와 모듈 컨텍스트 배열 s->ctx는 모두 클라이언트 연결의 메모리 풀(c->pool)에서 할당된다. 이 풀이 해제되면 세션과 컨텍스트 배열도 함께 사라진다.

클라이언트가 로그인 명령을 보내면, nginx는 auth_http에 지정된 HTTP 인증 서비스로 별도의 HTTP 연결(이하 인증 연결)을 열어 로그인 정보의 유효성을 조회한다. 조회 결과가 올 때까지 클라이언트 연결과 인증 연결이 동시에 유지된다.

인증 조회를 시작하는 ngx_mail_auth_http_init() 함수는 인증 연결의 data 필드에 클라이언트 세션 s를, pool 필드에 클라이언트 메모리 풀을 직접 대입한다. 인증 연결이 세션의 소유가 아닌 세션의 참조만 갖는 구조이므로, 세션이 먼저 해제되면 인증 연결은 해제된 메모리를 가리키게 된다.

nginx의 각 연결에는 read handler와 write handler가 있다. 이벤트 루프가 소켓에서 읽기 가능/쓰기 가능 이벤트를 감지하면 해당 핸들러를 호출한다. 메일 프록시에서 인증 조회를 시작할 때 각 핸들러는 다음과 같이 설정된다.

연결

read handler

write handler

클라이언트

ngx_mail_auth_http_block_read (인증 중 추가 입력 차단)

ngx_mail_send (교체되지 않음, 기존 그대로)

인증 연결

ngx_mail_auth_http_read_handler

ngx_mail_auth_http_write_handler

클라이언트의 read handler는 인증 전용으로 교체되지만, write handler는 기존의 ngx_mail_send()가 그대로 유지된다. ngx_mail_auth_http_block_read에는 오류 발생 시 인증 연결을 정리하는 코드가 있지만, ngx_mail_send()의 오류 처리에는 인증 연결 정리 코드가 없다. 이것이 취약점의 근본 원인이다.

// src/mail/ngx_mail_auth_http_module.c — 216~222 (ngx_mail_auth_http_init)
ctx->peer.connection->data = s;                         // auth connection → references client session
ctx->peer.connection->pool = s->connection->pool;       // shares the session's memory pool

s->connection->read->handler = ngx_mail_auth_http_block_read;    // read handler replaced
ctx->peer.connection->read->handler = ngx_mail_auth_http_read_handler;
ctx->peer.connection->write->handler = ngx_mail_auth_http_write_handler;
// NOTE: s->connection->write->handler is NOT replaced
// src/mail/ngx_mail_auth_http_module.c — 216~222 (ngx_mail_auth_http_init)
ctx->peer.connection->data = s;                         // auth connection → references client session
ctx->peer.connection->pool = s->connection->pool;       // shares the session's memory pool

s->connection->read->handler = ngx_mail_auth_http_block_read;    // read handler replaced
ctx->peer.connection->read->handler = ngx_mail_auth_http_read_handler;
ctx->peer.connection->write->handler = ngx_mail_auth_http_write_handler;
// NOTE: s->connection->write->handler is NOT replaced
// src/mail/ngx_mail_auth_http_module.c — 216~222 (ngx_mail_auth_http_init)
ctx->peer.connection->data = s;                         // auth connection → references client session
ctx->peer.connection->pool = s->connection->pool;       // shares the session's memory pool

s->connection->read->handler = ngx_mail_auth_http_block_read;    // read handler replaced
ctx->peer.connection->read->handler = ngx_mail_auth_http_read_handler;
ctx->peer.connection->write->handler = ngx_mail_auth_http_write_handler;
// NOTE: s->connection->write->handler is NOT replaced

이전 응답의 전송이 완료되지 않은 상태에서는 ngx_mail_send()가 write event를 등록해 둔다. 이때 client가 로그인 명령을 보내면서 동시에 TCP reset을 보내면, epoll_wait 한 번의 반환에서 read event와 write event가 함께 보고된다. nginx는 먼저 read handler를 호출하고, read handler는 로그인 명령을 읽어 인증 조회를 시작한다. 인증 연결이 열리고 ctx->peer.connection->data가 세션 s를 가리키게 된다. 곧바로 write handler(ngx_mail_send)가 호출되어 대기 중인 응답 전송을 시도하지만, 연결이 이미 reset된 상태이므로 실패한다.

// src/mail/ngx_mail_handler.c — 812~815 (ngx_mail_send)
if (n == NGX_ERROR) {
    ngx_mail_close_connection(c);          // close client connection
    return;
}
// src/mail/ngx_mail_handler.c — 812~815 (ngx_mail_send)
if (n == NGX_ERROR) {
    ngx_mail_close_connection(c);          // close client connection
    return;
}
// src/mail/ngx_mail_handler.c — 812~815 (ngx_mail_send)
if (n == NGX_ERROR) {
    ngx_mail_close_connection(c);          // close client connection
    return;
}
// src/mail/ngx_mail_handler.c — 966~972 (ngx_mail_close_connection)
c->destroyed = 1;

pool = c->pool;

ngx_close_connection(c);                   // close TCP connection

ngx_destroy_pool(pool);                    // free session s and module context array
// src/mail/ngx_mail_handler.c — 966~972 (ngx_mail_close_connection)
c->destroyed = 1;

pool = c->pool;

ngx_close_connection(c);                   // close TCP connection

ngx_destroy_pool(pool);                    // free session s and module context array
// src/mail/ngx_mail_handler.c — 966~972 (ngx_mail_close_connection)
c->destroyed = 1;

pool = c->pool;

ngx_close_connection(c);                   // close TCP connection

ngx_destroy_pool(pool);                    // free session s and module context array

ngx_destroy_pool()이 실행되면 세션 s와 세션에 연결된 모듈 컨텍스트 배열이 모두 해제된다. 그러나 인증 연결은 별도의 연결이므로 이 과정에서 닫히지 않고, 그 data 필드는 여전히 해제된 세션을 가리킨다.

이후 인증 서비스의 응답이 도착하거나 타임아웃이 발생하면 인증 연결의 핸들러가 실행된다.

// src/mail/ngx_mail_auth_http_module.c — 307~313 (ngx_mail_auth_http_read_handler)
c = rev->data;
s = c->data;                               // already-freed session
/* ... */
ctx = ngx_mail_get_module_ctx(s, ngx_mail_auth_http_module);   // accesses freed s->ctx
// src/mail/ngx_mail_auth_http_module.c — 307~313 (ngx_mail_auth_http_read_handler)
c = rev->data;
s = c->data;                               // already-freed session
/* ... */
ctx = ngx_mail_get_module_ctx(s, ngx_mail_auth_http_module);   // accesses freed s->ctx
// src/mail/ngx_mail_auth_http_module.c — 307~313 (ngx_mail_auth_http_read_handler)
c = rev->data;
s = c->data;                               // already-freed session
/* ... */
ctx = ngx_mail_get_module_ctx(s, ngx_mail_auth_http_module);   // accesses freed s->ctx

해제된 세션 영역이 공격자가 제어하는 데이터(예: 다른 IMAP 연결의 비밀번호)로 재할당되면, s->ctx가 가짜 컨텍스트를 가리키게 하고 그 컨텍스트의 handler 필드에 임의 주소를 넣어 명령 포인터를 제어할 수 있다.

8. 대응 방안

업데이트

nginx 1.31.9에는 5개 취약점의 수정 사항이 모두 포함되어 있어 업데이트로 앞서 소개한 5가지 취약점을 쉽게 조치할 수 있다. 다만 아래와 같은 주의사항이 존재한다.

  • 업데이트 후 nginx -s reload만으로는 실행 중인 바이너리가 교체되지 않으므로, nginx를 재시작을 해야 한다.

  • 배포판 패키지로 설치한 경우, nginx -v에 표시되는 버전이 아닌 배포판 패키지 버전을 확인해야 한다. 배포판은 보안 수정을 백포트하므로, 패키지 버전이 올라가더라도 nginx 자체 버전은 그대로일 수 있다.

임시 완화책

CVE

완화책

CVE-2026-123007, CVE-2026-123633

HTTP/2 비활성화. http2 off; (nginx 1.25.1+) 또는 listen에서 http2 파라미터 제거 (1.9.5~1.25.0)

CVE-2026-123634

고정 업스트림 그룹 사용으로 요청 시점의 DNS 조회 제거. mirror_request_body 변경만으로는 불충분

CVE-2026-121810

HTTP/3(QUIC) 비활성화. quic 리스너 제거, http3 off;, add_header Alt-Svc 'clear' always;

CVE-2026-113425

메일 프록시의 외부 접근 차단. 리스너를 루프백에 바인딩하거나 방화벽으로 제한

운영 환경 상 업데이트가 제한되는 경우, 각 취약점의 발생지점이 되는 기능을 비활성화하여 임시 조치가 가능하다. 모든 완화책은 설정 변경 후 nginx 재시작이 필요하며 reload만으로는 기존 연결이 이전 워커에서 계속 처리될 수 있으니 주의가 필요하다.

9. OFFen ASM NGINX2SHELL 취약점 스캐너

nginx2shell처럼 파급력이 높고 유명한 취약점의 경우 poc를 가장한 악성코드를 github 등에 공개하여 2차 피해가 발생하는 경우가 있다.
또한 악성코드가 아니더라도 신뢰할 수 없는 poc 혹은 scanner를 사용하여 취약환경에 대한 점검이 미흡하게 진행될 수 있다.

엔키화이트햇은 OFFen ASM 솔루션과 NGINX2SHELL 긴급 스캐너를 제공하고 있으며, 이를 통해 해당 취약점의 영향 여부를 안전하게 점검할 수 있다.

https://asm.offen.im/nginx2shell

10. 출처 및 참고

엔키화이트햇

엔키화이트햇

ENKI Whitehat
ENKI Whitehat

오펜시브 시큐리티 전문 기업, 공격자 관점으로 깊이가 다른 보안을 제시합니다.

오펜시브 시큐리티 전문 기업, 공격자 관점으로 깊이가 다른 보안을 제시합니다.

隙のないセキュリティ設計の始まり、NO.1ホワイトハッカーのノウハウから

インシデント発生前、
今すぐ備えましょう

隙のないセキュリティ設計の始まり、
No.1ホワイトハッカーのノウハウから

インシデント発生前、
今すぐ備えましょう

隙のないセキュリティ設計の始まり、
No.1ホワイトハッカーのノウハウから

インシデント発生前、
今すぐ備えましょう

購読

コンテンツが役に立ったら? エンキーレターを購読しましょう!

Copyright © 2025. ENKI WhiteHat Co., Ltd. All rights reserved.

Copyright © 2025. ENKI WhiteHat Co., Ltd. All rights reserved.

Copyright © 2025. ENKI WhiteHat Co., Ltd. All rights reserved.