[PATCH] bcache: fix out-of-bounds write in bch_data_verify()
From: Hyeonjun Hong
Date: Thu Nov 26 2026 - 04:38:30 EST
bch_data_verify() sizes its check bio from bio_segments() of the original
read bio, which is an unsigned int. bio_kmalloc() takes an unsigned short,
so the count is truncated before bio_kmalloc() compares it against
BIO_MAX_INLINE_VECS. A read bio with 65536 segments is truncated to zero,
passes the limit check and gets a bio with no bio_vec space. bch_bio_map()
then fills in bio_vecs from bi_size without looking at bi_max_vecs and
writes far beyond the allocation.
A single read bio of this size reaches bcache through an io_uring
registered buffer, which the block layer attaches to the bio without
splitting. Reading 256 MiB from a cached device with verify enabled on a
KASAN/KFENCE kernel gives:
BUG: KFENCE: out-of-bounds write in bch_bio_map+0x132/0x420
Out-of-bounds write at 0x00000000cb5c6057 (132B right of kfence-#252):
bch_bio_map+0x132/0x420
bch_data_verify+0x3d2/0xc40
cached_dev_read_done+0x6d4/0x890
process_one_work+0xafd/0x1ee0
kfence-#252: 0x000000008ee01c90-0x000000001f8e8fd6, size=120, cache=kmalloc-128
allocated by task 12 on cpu 0 at 63.371786s (0.000577s ago):
bio_kmalloc+0x45/0x80
bch_data_verify+0x2be/0xc40
followed by a general protection fault and panic. A 255 MiB read is not
affected because its truncated count still exceeds BIO_MAX_INLINE_VECS and
bio_kmalloc() returns NULL.
The verify path needs CONFIG_BCACHE_DEBUG and the verify attribute to be
set through sysfs.
Check the segment count before it is narrowed and skip verification of
bios that are too large, which is what already happens for every other
count above BIO_MAX_INLINE_VECS.
AI tools assisted the source audit, reproducer construction and patch
drafting.
Fixes: 0f2e6ab851ae ("block: turn the nr_iovecs argument to bio_alloc* into an unsigned short")
Reported-by: Seojin An <love09010224@xxxxxxxxx>
Reported-by: GEONWOO HAN <gunwoo9643@xxxxxxxxx>
Cc: stable@xxxxxxxxxxxxxxx
Signed-off-by: Hyeonjun Hong <hyeonjunhong330@xxxxxxxxx>
---
drivers/md/bcache/debug.c | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/drivers/md/bcache/debug.c b/drivers/md/bcache/debug.c
index 2691a5da3368..fa665b4628b1 100644
--- a/drivers/md/bcache/debug.c
+++ b/drivers/md/bcache/debug.c
@@ -112,6 +112,14 @@ void bch_data_verify(struct cached_dev *dc, struct bio *bio)
struct bio_vec bv, cbv;
struct bvec_iter iter, citer = { 0 };
+ /*
+ * bio_kmalloc() takes an unsigned short, so a larger segment count
+ * would be truncated before its own limit check. Skip verification
+ * of bios which cannot be represented.
+ */
+ if (nr_segs > BIO_MAX_INLINE_VECS)
+ return;
+
check = bio_kmalloc(nr_segs, GFP_NOIO);
if (!check)
return;