[BUG]
Running "btrfs rescue fix-data-checksum" on a filesystem with a data
checksum mismatch triggers a heap buffer overflow:
==3692==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x502000000190
READ of size 8 at 0x502000000190 thread T0
#0 set_bit kernel-lib/bitops.h:32
#1 add_corrupted_block cmds/rescue-fix-data-checksum.c:99
#2 verify_one_data_block cmds/rescue-fix-data-checksum.c:143
#3 iterate_one_csum_item cmds/rescue-fix-data-checksum.c:178
#4 iterate_csum_root cmds/rescue-fix-data-checksum.c:252
#5 btrfs_recover_fix_data_checksum cmds/rescue-fix-data-checksum.c:510
0x502000000191 is located 0 bytes after 1-byte region [0x502000000190,0x502000000191)
allocated by thread T0 here:
#0 calloc
#1 add_corrupted_block cmds/rescue-fix-data-checksum.c:94
[CAUSE]
BITS_TO_LONGS() returns the number of unsigned longs needed to hold the
given amount of bits, not the number of bytes. But the value is passed as
the byte size to calloc():
last->error_mirror_bitmap = calloc(1, BITS_TO_LONGS(num_mirrors));
For any sane number of mirrors this allocates a single byte, while
set_bit() accesses the bitmap in unsigned long units, thus reading and
writing 8 bytes out of a 1 byte allocation.
[FIX]
Use bitmap_zalloc() from kernel-lib/bitmap.h, which does the size
calculation for the caller, and pair it with bitmap_free() when the
record is released.
Fixes: 0e999c9bd3e7 ("btrfs-progs: introduce "btrfs rescue fix-data-checksum"")
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Sidong Yang <sidong.yang@furiosa.ai>
Signed-off-by: David Sterba <dsterba@suse.com>
#include "kerncompat.h"
#include <ctype.h>
+#include "kernel-lib/bitmap.h"
#include "kernel-shared/disk-io.h"
#include "kernel-shared/ctree.h"
#include "kernel-shared/volumes.h"
last = calloc(1, sizeof(*last));
if (!last)
return -ENOMEM;
- last->error_mirror_bitmap = calloc(1, BITS_TO_LONGS(num_mirrors));
+ last->error_mirror_bitmap = bitmap_zalloc(num_mirrors);
if (!last->error_mirror_bitmap) {
free(last);
return -ENOMEM;
entry = list_entry(corrupted_blocks.next, struct corrupted_block, list);
list_del_init(&entry->list);
- free(entry->error_mirror_bitmap);
+ bitmap_free(entry->error_mirror_bitmap);
free(entry);
}
}