Skip to content

Crash in UnicodeError.__str__ with attributes have custom __str__ #128974

@picnixz

Description

@picnixz

Crash report

What happened?

class Evil(str): def __str__(self): del exc.object return 'evil' exc = UnicodeEncodeError(Evil(), "object", 0, 0, Evil()) str(exc)

results in Segmentation fault (core dumped). Another possibility for a crash:

class Evil(str): def __str__(self): del exc.object return 'evil' exc = UnicodeEncodeError(Evil(), "object", 0, 0, Evil()) str(exc)

results in

python: ./Include/cpython/unicodeobject.h:286: PyUnicode_GET_LENGTH: Assertion `PyUnicode_Check(op)' failed. Aborted (core dumped) 

The segmentation fault is quite easy to fix:

reason_str = PyObject_Str(exc->reason); if (reason_str == NULL) { goto done; } encoding_str = PyObject_Str(exc->encoding); if (encoding_str == NULL) { goto done; } Py_ssize_t len = PyUnicode_GET_LENGTH(exc->object);

It occurs in PyUnicode_GET_LENGTH(exc->object);. And the reason is that PyObject_Str(...) may call artrbitary code.

I have a PR ready that I will post soon.

See #128975 (comment) for the rationale of not backporting it.

CPython versions tested on:

CPython main branch

Linked PRs

Metadata

Metadata

Assignees

Labels

interpreter-core(Objects, Python, Grammar, and Parser dirs)topic-unicodetype-crashA hard crash of the interpreter, possibly with a core dump

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions