python / python/cpython

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

Aberta
#148,382 6 comentários 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

extension-modules type-crash
Linguagem predominante
Python
Estrelas
77.2k
Forks
35.9k
Métricas de merge de PRs
Métricas de PR pendentes

Descrição

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

Guia de contribuição

Abrir o guia de contribuição

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Direção de pesquisa

Comece em Modules/_decimal/_decimal.c, na macro CURRENT_CONTEXT por volta da linha 1951, e depois inspecione seus mais de 20 pontos de chamada e a segunda macro usada sem WITH_DECIMAL_CONTEXTVAR. Execute o reproducer fornecido do warning handler em um build main do CPython. Está concluído quando o caminho de callback reproduzido não usar mais um contexto liberado em nenhuma das duas configurações.

Escrita pelo modelo de indexação a partir do texto da issue.

Avaliação

Stack de tecnologia
c, python
Domínio
security
Tipo de issue
Bug
Dificuldade
4/5
Tempo estimado
3-5 dias
Status de atividade
Pouca atividade
Clareza
Razoavelmente clara
Facilidade para iniciantes
45/100

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.