python / python/cpython

`_decimal::CURRENT_CONTEXT`: UAF via borrowed reference across Python callbacks

未关闭
#148,382 6 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

extension-modules type-crash
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Crash report

Originally reported by @PidSS as a security advisory

What happened?

The CURRENT_CONTEXT() macro in Modules/_decimal/_decimal.c:1951 obtains a new reference from PyContextVar_Get(), then immediately calls Py_DECREF, leaving a borrowed reference. If Python code executes before the context pointer is next used — via warning handlers, GC finalizers, instancecheck, etc. — and that code calls decimal.setcontext(), the old context is freed while C code still holds a dangling pointer. The macro is used at 20+ call sites covering virtually every decimal operation.

Original reproducer (I will try to make a shorter one):

import decimal, warnings, gc, sys, ctypes

gc.disable()
ctx = decimal.getcontext()
CTX_ID, CTX_SIZE = id(ctx), sys.getsizeof(ctx)
del ctx  # refcount = 1, held only by ContextVar HAMT

def evil_warning_handler(message, category, filename, lineno, file=None, line=None):
    if 'Format specifier' not in str(message):
        return
    ctx = decimal.getcontext()                       # refcount -> 2
    decimal.setcontext(decimal.Context(prec=999))    # HAMT ref dropped -> 1
    del ctx                                          # refcount -> 0, FREED
    spray = [bytearray(b'\xCC' * (CTX_SIZE - 32)) for _ in range(100000)]

warnings.showwarning = evil_warning_handler
warnings.filterwarnings('always', category=DeprecationWarning)
format(decimal.Decimal('123.456'), 'N')

FTR, I saw that we have this macro twice, but it depends on whether we have WITH_DECIMAL_CONTEXTVAR. If I build Python with --without-decimal-contextvar, I also have a crash so it's a bit weird.

Related but not with the same root cause: https://github.com/python/cpython/issues/146011.

CPython versions tested on:

CPython main branch

Operating systems tested on:

No response

Output from running 'python -VV' on the command line:

No response

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 Modules/_decimal/_decimal.c 中约第 1951 行的 CURRENT_CONTEXT 宏开始,然后检查它的 20 多个调用点,以及在不使用 WITH_DECIMAL_CONTEXTVAR 的情况下使用的另一个宏。在 CPython main 构建上运行随附的 warning-handler reproducer。当复现出的 callback 路径在两种配置中都不再使用已释放的 context 时,即表示完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
c, python
领域
security
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
冷清
描述清晰度
基本清楚
新手友好度
45/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。