From d278b460f3167c791e8d419580d30f04a296f30b Mon Sep 17 00:00:00 2001 From: Angus Gratton Date: Wed, 31 Jan 2024 18:01:30 +1100 Subject: [PATCH] py/stream: Check for stream read function returning too many bytes. This only happens if the underlying stream implementation is malformed, but results in unsigned integer overflow and out of bounds read otherwise. Second fix for #13046 - allows for possibility an invalid result comes back from a different stream implementation. This work was funded through GitHub Sponsors. Signed-off-by: Angus Gratton --- py/stream.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/py/stream.c b/py/stream.c index aa905ca8cc..b0fd712c26 100644 --- a/py/stream.c +++ b/py/stream.c @@ -64,6 +64,11 @@ mp_uint_t mp_stream_rw(mp_obj_t stream, void *buf_, mp_uint_t size, int *errcode if (out_sz == 0) { return done; } + if (out_sz != MP_STREAM_ERROR && out_sz > size) { + // This can only happen if the filesystem implementation returned invalid out_sz + *errcode = MP_EINVAL; + out_sz = MP_STREAM_ERROR; + } if (out_sz == MP_STREAM_ERROR) { // If we read something before getting EAGAIN, don't leak it if (mp_is_nonblocking_error(*errcode) && done != 0) {