From 880dd0a1cd63695ca2c1766746457074032f456d Mon Sep 17 00:00:00 2001 From: Jeff Epler Date: Fri, 8 Aug 2025 08:53:14 -0500 Subject: [PATCH] vfs: Check that open() resulted in a file-like object. That is, an object whose type defines the protocol slot. Note that due to protocol confusion, a variant of the original crasher that returned e.g., a machine.Pin instance could still lead to a crash. (#17852) Closes: #17841 Signed-off-by: Jeff Epler --- extmod/vfs.c | 7 ++++++- tests/extmod/vfs_open_error.py | 19 +++++++++++++++++++ tests/extmod/vfs_open_error.py.exp | 1 + 3 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 tests/extmod/vfs_open_error.py create mode 100644 tests/extmod/vfs_open_error.py.exp diff --git a/extmod/vfs.c b/extmod/vfs.c index aebf5ed295b3b..99bffd5c41ec8 100644 --- a/extmod/vfs.c +++ b/extmod/vfs.c @@ -338,7 +338,12 @@ mp_obj_t mp_vfs_open(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) #endif mp_vfs_mount_t *vfs = lookup_path(args[ARG_file].u_obj, &args[ARG_file].u_obj); - return mp_vfs_proxy_call(vfs, MP_QSTR_open, 2, (mp_obj_t *)&args); + mp_obj_t result = mp_vfs_proxy_call(vfs, MP_QSTR_open, 2, (mp_obj_t *)&args); + const mp_obj_type_t *type = mp_obj_get_type(vfs->obj); + if (!MP_OBJ_TYPE_HAS_SLOT(type, protocol)) { + mp_raise_TypeError(NULL); + } + return result; } MP_DEFINE_CONST_FUN_OBJ_KW(mp_vfs_open_obj, 0, mp_vfs_open); diff --git a/tests/extmod/vfs_open_error.py b/tests/extmod/vfs_open_error.py new file mode 100644 index 0000000000000..c372d8f3afb3e --- /dev/null +++ b/tests/extmod/vfs_open_error.py @@ -0,0 +1,19 @@ +import os +import vfs + + +class Filesystem: + def mount(self, readonly, mkfs): + pass + + def open(self, file, mode): + return None # violates vfs contract + + +fs = Filesystem() +vfs.mount(fs, "/test_mnt") +try: + execfile("/test_mnt/test.py") + print("ExecFile succeeded") +except TypeError: + print("TypeError") diff --git a/tests/extmod/vfs_open_error.py.exp b/tests/extmod/vfs_open_error.py.exp new file mode 100644 index 0000000000000..6002b71c56ea0 --- /dev/null +++ b/tests/extmod/vfs_open_error.py.exp @@ -0,0 +1 @@ +TypeError