CVE-2026-85748 CRITICAL 9.9 난이도Difficulty 중급Intermediate

MariaDB SYS_REFCURSOR 커서 배열 재할당이 남긴 댕글링 포인터MariaDB SYS_REFCURSOR: dangling pointers from cursor-array reallocation

공식 참조Official references: NVDCVE.org

CVE-2026-85748는 MariaDB Server의 Use After Free(CWE-416) 취약점으로, CVSS 9.9(CRITICAL)입니다. 영향 버전: 12.3.1 – 12.3.2, 13.0.1. 수정 버전: 12.3.3, 13.0.2.CVE-2026-85748 is an Use After Free (CWE-416) vulnerability in MariaDB Server, rated CVSS 9.9 (CRITICAL). Affected: 12.3.1 – 12.3.2, 13.0.1. Fixed in: 12.3.3, 13.0.2.

제품Product MariaDB Server
영향 버전Affected 12.3.1 – 12.3.2, 13.0.1
수정 버전Fixed in 12.3.3, 13.0.2
심각도Severity CVSS 9.9 CRITICAL
취약점 유형Weakness CWE-416 Use After Free
공격 조건Attack conditions 원격 (네트워크) · 일반 권한 계정 필요 · 사용자 상호작용 불필요Remote (network) · Low-privilege account · No user interaction

1. TL;DR

  • MariaDB 의 SYS_REFCURSOR(참조 커서) 구현에서 발생한 Use-After-Free 입니다. 세션당 커서를 담는 배열이 커지면서 재할당될 때, 옛 메모리 주소를 쥔 포인터가 갱신되지 않고 남습니다.
  • 벤더 어드바이저리에 따르면, 다수의 SYS_REFCURSOR 를 연 뒤 그중 하나를 fetch 할 때 UAF 가 발생할 수 있습니다. 어드바이저리는 이를 “다중 취약점 익스플로잇 체인”의 일부로 쓸 수 있다고 설명합니다. 이 결함 하나만으로 RCE 가 가능하다고는 하지 않습니다.
  • 어드바이저리 기준 영향 버전은 12.3.1–12.3.2 와 13.0.1 이고, 수정 버전은 12.3.3 과 13.0.2 입니다. 같은 어드바이저리는 우회책이 없으니 즉시 업그레이드하라고 권고합니다.
  • CVSS 3.1 은 9.9(Critical, AV:N/AC:L/PR:L/UI:N/S:C)입니다. 점수는 높지만, 어드바이저리 문구상 실제 코드 실행은 다른 결함과의 결합을 전제로 합니다.

2. Flaw 분류

항목값
1차 CWECWE-416 Use After Free (NVD, GHSA 모두 동일)
공격 벡터네트워크. 인증된 저권한 DB 계정이 SQL 로 SYS_REFCURSOR 를 다수 열고 fetch 합니다.
영향메모리 안전성 위반(UAF). 어드바이저리는 다른 취약점과 결합하면 원격 코드 실행으로 이어질 수 있다고 설명합니다. 단독 영향은 커밋 제목 기준으로 서버 크래시이며, 그 이상은 공개 정보로 확인되지 않았습니다.
전제서버에 로그인 가능한 계정이 있어야 하고, 영향 버전(12.3.1–12.3.2, 13.0.1)을 쓰고 있어야 합니다. 필요한 구체적 권한은 공개 정보로 확인되지 않았습니다.

3. 근본 원인

한 줄로 줄이면 “재할당될 수 있는 컨테이너의 요소 주소를 장기간 들고 있었다” 입니다. 수정 커밋 두 개의 메시지를 보면 같은 뿌리에서 나온 두 경로가 있습니다.

3.1 select_result 포인터 (MDEV-40396)

커밋 9b075b2의 메시지에 따르면 세션의 커서 배열(THD::m_statement_cursor)이 alloc_dynamic 으로 크기가 바뀌면 모든 sp_cursor::result 의 메모리 위치가 바뀝니다. 그런데 Server_side_cursor 는 생성자에서 받은 sp_cursor::result 의 주소를 select_result * 멤버로 저장해 두고 있었습니다. 재할당 뒤에는 이 멤버가 이미 해제된 옛 위치를 가리키게 됩니다. 이 포인터는 헤더 주석상 fetch 때 행을 내보내는 목적지(row destination)로 쓰입니다.

3.2 요소 포인터 (MDEV-40639)

커밋 91156c3의 메시지는 다음 상황을 설명합니다.

  • 루틴 A() 가 SELECT 목록에 함수 B() 가 들어 있는 SYS_REFCURSOR 를 엽니다.
  • B() 도 내부에서 SYS_REFCURSOR 를 엽니다.

이때 B() 실행 중에 커서 배열이 재할당될 수 있습니다. 그러면 A() 쪽 sp_instr_copen_by_ref::exec_core() 안에 있던 sp_cursor_array_element 포인터가 모두 무효가 됩니다. 커밋 메시지는 이를 “crash”로 부르고, 어드바이저리는 UAF 로 분류합니다.

두 경우 모두 Dynamic_array<T> 가 요소를 값으로 저장하므로 재할당 때 요소 자체가 이동합니다. 그런데 그 요소의 주소를 다른 객체나 스택이 계속 보관했습니다. 이것이 CWE-416 이 만들어지는 구조입니다.

4. 익스플로잇 흐름(개념)

아래는 결함이 UAF 로 이어지는 단계만 개념적으로 정리한 것입니다. 구체적인 SQL 과 입력, 힙 조작은 일부러 쓰지 않았습니다.

  1. 다수의 SYS_REFCURSOR 열기 — 커서 배열 증가
  2. 배열 재할당 — 요소 메모리가 새 위치로 이동
  3. 옛 주소를 쥔 포인터 잔존 — stale
  4. 해당 커서 fetch — 해제된 영역 참조
  5. 메모리 손상 — 결합 시 RCE 가능성
개념 흐름도 — 실행 가능한 페이로드가 아닙니다
  1. 저권한 세션이 SYS_REFCURSOR 를 많이 열어 세션의 커서 배열을 커지게 합니다.
  2. 배열이 커지면서 재할당되고, 요소가 새 메모리로 옮겨 갑니다.
  3. 커서 객체나 실행 중인 루틴이 쥐고 있던 옛 주소는 갱신되지 않습니다.
  4. 이후 커서 fetch 등으로 그 옛 주소를 사용하면 해제된 메모리에 접근합니다.
  5. 해제된 메모리 접근은 최소한 크래시를 낳습니다. 어드바이저리는 다른 결함과 결합하면 완전한 RCE 로 이어질 수 있다고만 밝히며, 그 구체적 방법은 공개 정보로 확인되지 않았습니다.

5. 트리거 조건

  • 영향 버전은 어드바이저리 기준으로 12.3.1–12.3.2 와 13.0.1 입니다. NVD 와 Jira 의 범위는 이와 조금 다릅니다(REVIEW_NOTES 참조).
  • 서버에 접속해 SQL 로 SYS_REFCURSOR 를 다룰 수 있는 계정이 필요합니다. 필요한 구체적 권한은 공개 정보로 확인되지 않았습니다.
  • 커서 배열이 재할당될 만큼 많은 SYS_REFCURSOR 가 열려 있어야 합니다.
  • 두 가지 경로가 있습니다. 하나는 이미 열린 커서가 옛 select_result 주소를 쥔 채 fetch 하는 경로입니다. 다른 하나는 OPEN ... FOR SELECT 의 SELECT 목록 안에서 호출된 함수가 자체적으로 커서를 열어 배열을 재할당시키는 경로입니다(3장 참조).
  • 사용자 상호작용은 필요 없습니다(UI:N).

6. 패치 분석

수정 방향은 “포인터가 재할당 대상에 직접 묶이지 않게 한다” 입니다. 실제 diff 를 두 커밋에서 확인했고, 핵심만 인용합니다.

6.1 select_result * 를 멤버로 저장하지 않기 (9b075b2)

sql/sql_cursor.h에서 Server_side_cursor 의 멤버를 없애고, open() 과 fetch() 가 호출 시점의 유효한 주소를 인자로 받게 바꿨습니다.

+4−7cpp
class Server_side_cursor: protected Query_arena
{
protected:
  /** Row destination used for fetch */
  select_result *result;
public:
  Server_side_cursor(MEM_ROOT *mem_root_arg, select_result *result_arg)
  :Query_arena(mem_root_arg, STMT_INITIALIZED), result(result_arg)
  Server_side_cursor(MEM_ROOT *mem_root_arg)
  :Query_arena(mem_root_arg, STMT_INITIALIZED)
{}
  virtual int open(JOIN *top_level_join)= 0;
  virtual void fetch(ulong num_rows)= 0;
  virtual int open(select_result *result, JOIN *top_level_join)= 0;
  virtual void fetch(select_result *result, ulong num_rows)= 0;

호출부도 같이 바뀌었습니다. 예를 들어 sp_cursor::fetch() 는 이제 server_side_cursor->fetch(&result, 1) 을 호출합니다. 옛 주소를 저장하던 멤버가 사라졌으므로 “저장된 stale 포인터”라는 4장의 3단계가 끊깁니다. &result 는 fetch 시점의 현재 위치라서 항상 유효합니다.

6.2 요소를 가리키는 포인터 배열로 바꾸기 (91156c3)

sql/sp_cursor.h에서 배열이 요소 값 대신 포인터를 저장합니다. 요소는 new 로 따로 할당합니다.

+1−1cpp
class sp_cursor_array: public Dynamic_array<sp_cursor_array_element>
class sp_cursor_array: public Dynamic_array<sp_cursor_array_element*>
+5−0cpp
void free(THD *thd)
{
  close(thd);
  for (uint i= 0; i < (uint) size(); i++)
  {
    DBUG_ASSERT(at(i));
    delete at(i);
  }
  free_memory();
}

sql/sp_cursor.cc의 append() 에서도 요소를 따로 할당합니다. 새 요소를 new sp_cursor_array_element() 로 만들어 그 포인터를 배열에 넣습니다.

이제 재할당되는 것은 포인터 배열뿐이고, 요소 객체는 처음 할당된 주소에 그대로 남습니다. 커밋 메시지도 같은 설명입니다. 그래서 A() 가 쥔 요소 주소는 B() 안에서 배열이 늘어나도 유효합니다. 2단계(재할당 때 요소 이동)가 더 이상 일어나지 않아 흐름이 끊깁니다. free() 에 delete 루프가 추가된 것은 소유권이 배열 밖의 힙 객체로 옮겨졌기 때문입니다.

두 커밋은 각각 회귀 테스트(mysql-test/main/sp-sys_refcursor.test 등)도 추가했습니다. 이 글에서는 테스트 내용을 옮기지 않았습니다.

7. 탐지·완화

즉시 조치

  • 12.3.x 는 12.3.3 이상, 13.0.x 는 13.0.2 이상으로 업그레이드합니다. 어드바이저리는 우회책이 없다고 밝혔습니다.
  • 현재 버전은 SELECT VERSION(); 으로 확인합니다. 영향 범위는 5장의 기준(12.3.1–12.3.2, 13.0.1)과 REVIEW_NOTES 의 불일치를 함께 보고 판단합니다.
  • 업그레이드 전까지는 아래 일반 원칙으로 노출을 줄입니다. 이 결함에 대한 효과는 벤더가 검증한 것이 아닙니다.
    • DB 포트를 신뢰된 네트워크로 제한합니다.
    • 불필요한 계정을 정리하고 권한을 최소화합니다.

탐지

  • 에러 로그에서 mariadbd 의 비정상 종료(시그널 기반 크래시)와 재시작을 확인합니다. 커밋 제목이 “crash”를 말하므로 크래시가 가장 눈에 띄는 증상일 수 있습니다.
  • 크래시 직전 같은 계정이 SYS_REFCURSOR 를 반복해서 여는 세션인지 감사 로그나 general log 로 확인합니다. 이는 일반적인 조사 방법이고, 공식 탐지 시그니처는 공개 정보로 확인되지 않았습니다.
  • 저권한 계정에서 온 비정상적으로 많은 커서 사용과 반복 크래시를 함께 경보로 묶는 것을 검토합니다.

격리된 실습(로컬 Docker 랩)

  • 재현은 인터넷과 분리된 로컬 Docker 랩에서만 합니다. --internal 네트워크나 --network none 으로 외부 통신을 막고, 운영 데이터와 자격 증명은 넣지 않습니다. 공개 네트워크에 있는 서버를 대상으로 시험하지 않습니다.
  • 학습 목표는 공격이 아니라 원리 확인입니다.
    • 영향 버전과 수정 버전을 각각 빌드합니다. 가능하면 AddressSanitizer 로 빌드합니다.
    • 저장소에 포함된 회귀 테스트 sp-sys_refcursor 를 MTR(mysql-test-run)로 돌립니다. 수정 전후로 결과가 어떻게 달라지는지 비교합니다.
    • ASan 리포트에서 해제 지점(재할당)과 사용 지점(fetch)의 스택을 읽어, 3장의 설명과 맞춰 봅니다.
  • 코드 실행 체인을 구성하거나 시도하는 것은 이 실습의 범위가 아닙니다.

8. References

1. TL;DR

  • This is a Use-After-Free in MariaDB’s SYS_REFCURSOR (reference cursor) implementation. When the per-session array that holds cursors grows and is reallocated, a pointer still holding the old memory address is left un-updated.
  • According to the vendor advisory, a UAF can occur when you open many SYS_REFCURSORs and then fetch from one of them. The advisory explains it can be used as part of a “multi-vulnerability exploit chain.” It does not claim RCE is possible from this flaw alone.
  • Per the advisory, affected versions are 12.3.1–12.3.2 and 13.0.1, and the fixed versions are 12.3.3 and 13.0.2. The same advisory recommends upgrading immediately because there is no workaround.
  • CVSS 3.1 is 9.9 (Critical, AV:N/AC:L/PR:L/UI:N/S:C). The score is high, but per the advisory wording actual code execution presupposes being combined with another flaw.

2. Flaw classification

ItemValue
Primary CWECWE-416 Use After Free (same in both NVD and GHSA)
Attack vectorNetwork. An authenticated low-privilege DB account opens and fetches many SYS_REFCURSORs via SQL.
ImpactMemory-safety violation (UAF). The advisory explains it can lead to remote code execution when combined with another vulnerability. The standalone impact is a server crash per the commit titles; anything beyond that is not confirmed in public sources.
PrerequisitesAn account able to log into the server, and an affected version in use (12.3.1–12.3.2, 13.0.1). The specific privileges required are not confirmed in public sources.

3. Root cause

In one line: “it held the address of an element of a container that can be reallocated, for a long time.” The messages of the two fix commits show two paths from the same root.

3.1 The select_result pointer (MDEV-40396)

According to the message of commit 9b075b2, when the session’s cursor array (THD::m_statement_cursor) is resized with alloc_dynamic, the memory location of every sp_cursor::result changes. Yet Server_side_cursor had stored the address of the sp_cursor::result it received in its constructor as a select_result * member. After reallocation this member points at an already-freed old location. Per the header comment, this pointer is used as the row destination when fetching.

3.2 The element pointer (MDEV-40639)

The message of commit 91156c3 describes this situation:

  • Routine A() opens a SYS_REFCURSOR whose SELECT list contains a function B().
  • B() also opens a SYS_REFCURSOR internally.

The cursor array can be reallocated while B() runs. Then all sp_cursor_array_element pointers inside A()‘s sp_instr_copen_by_ref::exec_core() become invalid. The commit message calls this a “crash,” and the advisory classifies it as a UAF.

In both cases, because Dynamic_array<T> stores elements by value, the elements themselves move on reallocation. Yet the address of those elements was kept by another object or on the stack. This is the structure that creates CWE-416.

4. Exploit flow (conceptual)

Below is only the conceptual series of steps by which the flaw leads to a UAF. Concrete SQL, input, and heap grooming are deliberately omitted.

  1. Open many SYS_REFCURSORs — cursor array grows
  2. Array reallocation — element memory moves to a new location
  3. Pointer holding the old address remains — stale
  4. Fetch that cursor — references freed region
  5. Memory corruption — possible RCE when combined
Conceptual flow — not an executable payload
  1. A low-privilege session opens many SYS_REFCURSORs, growing the session’s cursor array.
  2. As the array grows it is reallocated, and the elements move to new memory.
  3. The old address held by a cursor object or a running routine is not updated.
  4. Later use of that old address, for example via a cursor fetch, accesses freed memory.
  5. Accessing freed memory produces at minimum a crash. The advisory only states it can lead to full RCE when combined with another flaw, and the concrete method is not confirmed in public sources.

5. Trigger conditions

  • Per the advisory, affected versions are 12.3.1–12.3.2 and 13.0.1. NVD’s and Jira’s ranges differ slightly (see REVIEW_NOTES).
  • An account able to connect and manipulate SYS_REFCURSOR via SQL is required. The specific privileges needed are not confirmed in public sources.
  • Enough SYS_REFCURSORs must be open for the cursor array to be reallocated.
  • There are two paths. One is an already-open cursor fetching while holding the old select_result address. The other is a function called from within the SELECT list of OPEN ... FOR SELECT opening its own cursor and triggering the array reallocation (see section 3).
  • No user interaction is needed (UI:N).

6. Patch analysis

The fix direction is “keep pointers from being tied directly to a reallocation target.” The actual diffs were reviewed in both commits; only the essentials are quoted.

6.1 Don’t store select_result * as a member (9b075b2)

In sql/sql_cursor.h, the member of Server_side_cursor is removed, and open() and fetch() now take the valid address at call time as an argument.

+4−7cpp
class Server_side_cursor: protected Query_arena
{
protected:
  /** Row destination used for fetch */
  select_result *result;
public:
  Server_side_cursor(MEM_ROOT *mem_root_arg, select_result *result_arg)
  :Query_arena(mem_root_arg, STMT_INITIALIZED), result(result_arg)
  Server_side_cursor(MEM_ROOT *mem_root_arg)
  :Query_arena(mem_root_arg, STMT_INITIALIZED)
{}
  virtual int open(JOIN *top_level_join)= 0;
  virtual void fetch(ulong num_rows)= 0;
  virtual int open(select_result *result, JOIN *top_level_join)= 0;
  virtual void fetch(select_result *result, ulong num_rows)= 0;

Call sites changed too. For example, sp_cursor::fetch() now calls server_side_cursor->fetch(&result, 1). Because the member that stored the old address is gone, step 3 of section 4 (“stored stale pointer”) is broken. &result is the current location at fetch time, so it is always valid.

6.2 Switch to an array of pointers to elements (91156c3)

In sql/sp_cursor.h, the array stores pointers instead of element values. Elements are allocated separately with new.

+1−1cpp
class sp_cursor_array: public Dynamic_array<sp_cursor_array_element>
class sp_cursor_array: public Dynamic_array<sp_cursor_array_element*>
+5−0cpp
void free(THD *thd)
{
  close(thd);
  for (uint i= 0; i < (uint) size(); i++)
  {
    DBUG_ASSERT(at(i));
    delete at(i);
  }
  free_memory();
}

append() in sql/sp_cursor.cc also allocates elements separately. It makes a new element with new sp_cursor_array_element() and puts that pointer into the array.

Now only the pointer array is reallocated, and the element objects stay at their originally allocated addresses. The commit message explains the same. So the element address held by A() stays valid even if the array grows inside B(). Step 2 (elements moving on reallocation) no longer happens, breaking the chain. The delete loop added to free() is because ownership moved to heap objects outside the array.

Each commit also added regression tests (mysql-test/main/sp-sys_refcursor.test, etc.). This write-up does not reproduce the test contents.

7. Detection & mitigation

Immediate actions

  • Upgrade 12.3.x to 12.3.3 or later and 13.0.x to 13.0.2 or later. The advisory states there is no workaround.
  • Check the current version with SELECT VERSION();. Decide using both the section 5 range (12.3.1–12.3.2, 13.0.1) and the mismatch noted in REVIEW_NOTES.
  • Until you upgrade, reduce exposure with the general principles below. Their effect on this specific flaw has not been validated by the vendor.
    • Restrict the DB port to a trusted network.
    • Clean up unnecessary accounts and minimize privileges.

Detection

  • Check the error log for abnormal termination (signal-based crash) and restarts of mariadbd. Since the commit titles say “crash,” a crash may be the most visible symptom.
  • Check whether the session that was repeatedly opening SYS_REFCURSORs just before a crash came from the same account, via the audit log or the general log. This is a general investigative method; no official detection signature is confirmed in public sources.
  • Consider combining abnormally heavy cursor use from a low-privilege account with repeated crashes into a single alert.

Isolated practice (local Docker lab)

  • Reproduce only in a local Docker lab isolated from the internet. Block outbound communication with an --internal network or --network none, and do not include production data or credentials. Do not test against any server on a public network.
  • The learning goal is understanding the principle, not an attack.
    • Build an affected version and a fixed version separately. Build with AddressSanitizer if possible.
    • Run the bundled regression test sp-sys_refcursor via MTR (mysql-test-run). Compare how the results differ before and after the fix.
    • Read the free site (reallocation) stack and the use site (fetch) stack from the ASan report, and line them up with the explanation in section 3.
  • Building or attempting a code-execution chain is out of scope for this exercise.

8. References