[PATCH] bcachefs: slab-use-after-free Read in bch2_sb_errors_from_cpu

From: Pei Li
Date: Tue Jun 25 2024 - 16:05:56 EST


Acquire fsck_error_counts_lock before accessing the critical section
protected by this lock.

syzbot has tested the proposed patch and the reproducer did not trigger
any issue.

Reported-by: syzbot+a2bc0e838efd7663f4d9@xxxxxxxxxxxxxxxxxxxxxxxxx
Closes: https://syzkaller.appspot.com/bug?extid=a2bc0e838efd7663f4d9
Signed-off-by: Pei Li <peili.dev@xxxxxxxxx>
---
Syzbot detected we are accessing free'd memory in
bch2_sb_errors_from_cpu().

It is caused by race condition when another task is freeing the array
protected by fsck_error_counts_lock.

This patch acquires fsck_error_counts_lock before accessing the entries
and get the current number of elements in the array.

syzbot has tested the proposed patch and the reproducer did not trigger any issue:

Tested on:

commit: 55027e68 Merge tag 'input-for-v6.10-rc5' of git://git...
git tree: upstream
console output: https://syzkaller.appspot.com/x/log.txt?x=1790a501980000
kernel config: https://syzkaller.appspot.com/x/.config?x=d6b9ee98d841760c
dashboard link: https://syzkaller.appspot.com/bug?extid=a2bc0e838efd7663f4d9
compiler: gcc (Debian 12.2.0-14) 12.2.0, GNU ld (GNU Binutils for Debian) 2.40
patch: https://syzkaller.appspot.com/x/patch.diff?x=1272faae980000

Note: testing is done by a robot and is best-effort only.
---
fs/bcachefs/sb-errors.c | 14 ++++++++++----
1 file changed, 10 insertions(+), 4 deletions(-)

diff --git a/fs/bcachefs/sb-errors.c b/fs/bcachefs/sb-errors.c
index bda33e59e226..c1270d790e43 100644
--- a/fs/bcachefs/sb-errors.c
+++ b/fs/bcachefs/sb-errors.c
@@ -110,19 +110,25 @@ void bch2_sb_error_count(struct bch_fs *c, enum bch_sb_error_id err)
void bch2_sb_errors_from_cpu(struct bch_fs *c)
{
bch_sb_errors_cpu *src = &c->fsck_error_counts;
- struct bch_sb_field_errors *dst =
- bch2_sb_field_resize(&c->disk_sb, errors,
- bch2_sb_field_errors_u64s(src->nr));
+ struct bch_sb_field_errors *dst;
unsigned i;

+ mutex_lock(&c->fsck_error_counts_lock);
+
+ dst = bch2_sb_field_resize(&c->disk_sb, errors,
+ bch2_sb_field_errors_u64s(src->nr));
+
if (!dst)
- return;
+ goto err;

for (i = 0; i < src->nr; i++) {
SET_BCH_SB_ERROR_ENTRY_ID(&dst->entries[i], src->data[i].id);
SET_BCH_SB_ERROR_ENTRY_NR(&dst->entries[i], src->data[i].nr);
dst->entries[i].last_error_time = cpu_to_le64(src->data[i].last_error_time);
}
+
+err:
+ mutex_unlock(&c->fsck_error_counts_lock);
}

static int bch2_sb_errors_to_cpu(struct bch_fs *c)

---
base-commit: 66cc544fd75c70b5ee74df87ab99acc45b835e69
change-id: 20240625-bug2-94405201c4c8

Best regards,
--
Pei Li <peili.dev@xxxxxxxxx>