Skip to content

Harden feed_data() buffer handling for memoryview input #157

Backlog

Description

@nevercodecorrect

I'm opening this mainly to ask whether you consider it worth fixing.
These are corner cases that I handcrafted, and practically, they cannot be triggered by data coming off the network; only by how the calling code handles the object it passes to feed_data().
If you'd rather keep the current fast path, feel free to close this.

feed_data() has a fast path for memoryview that borrows the view's internal Py_buffer instead of acquiring an export of its own (parser.pyx:213-220):

if PyMemoryView_Check(data):
    buf = PyMemoryView_GET_BUFFER(data)
    data_len = <size_t>buf.len
    err = cparser.llhttp_execute(self._cparser, <char*>buf.buf, data_len)

Because no export is held, nothing keeps the memory valid while llhttp reads it, and the view is never validated.
If the view is released before or during the call (for example by a callback that recycles a receive buffer), llhttp reads freed memory:

import httptools
 
ba = bytearray(b"GET /path HTTP/1.1\r\nHost: example.com\r\n\r\n" + b"X" * 4096)
mv = memoryview(ba)
mv.release()
ba.clear()
httptools.HttpRequestParser(object()).feed_data(mv)
ERROR: AddressSanitizer: heap-use-after-free READ of size 1
    #0 llhttp__internal__run           vendor/llhttp/src/llhttp.c:4045
    #1 llhttp__internal_execute        vendor/llhttp/src/llhttp.c:10260
    #2 __pyx_pw_9httptools_6parser_6parser_10HttpParser_11feed_data
freed by thread T0:
    bytearray_clear -> PyByteArray_Resize -> free (Objects/bytearrayobject.c:296)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions