Skip to contentSkip to conversation

btrfs: fix use-after-free in move_existing_remap()

PATCH Superseded Mark Harmstone 2 participants 2 messages Feb 25 Btrfs file system

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 btrfs: fix use-after-free in move_existing_remap()

Fix a potential use-after-free in move_existing_remap(): we're calling btrfs_put_block_group() on dest_bg, then passing it to btrfs_add_block_group_free_space() a few lines later.

Fixes bbea42dfb91f ("btrfs: move existing remaps before relocating block group")
---
 fs/btrfs/relocation.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
fs/btrfs/relocation.c +5 -2
index cc80760ba5e7..5a8644667620 100644
@@ -4295,14 +4295,17 @@ static int move_existing_remap(struct btrfs_fs_info *fs_info,
 	bg_needs_free_space = test_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE,
 				       &dest_bg->runtime_flags);
 	mutex_unlock(&dest_bg->free_space_lock);
-	btrfs_put_block_group(dest_bg);
 
 	if (bg_needs_free_space) {
 		ret = btrfs_add_block_group_free_space(trans, dest_bg);
-		if (unlikely(ret))
+		if (unlikely(ret)) {
+			btrfs_put_block_group(dest_bg);
 			goto end;
+		}
 	}
 
+	btrfs_put_block_group(dest_bg);
+
 	ret = btrfs_remove_from_free_space_tree(trans, dest_addr, dest_length);
 	if (unlikely(ret)) {
 		btrfs_remove_from_free_space_tree(trans, new_addr, dest_length);
Signature · 1 line
2.52.0
#1 lore raw
Quoted 26 lines · Mark Harmstone

Fix a potential use-after-free in move_existing_remap(): we're calling btrfs_put_block_group() on dest_bg, then passing it to btrfs_add_block_group_free_space() a few lines later.

Fixes bbea42dfb91f ("btrfs: move existing remaps before relocating block group")
---
  fs/btrfs/relocation.c | 7 +++++--
  1 file changed, 5 insertions(+), 2 deletions(-)
fs/btrfs/relocation.c +1 -2
index cc80760ba5e7..5a8644667620 100644
@@ -4295,14 +4295,17 @@ static int move_existing_remap(struct btrfs_fs_info *fs_info,
  	bg_needs_free_space = test_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE,
  				       &dest_bg->runtime_flags);
  	mutex_unlock(&dest_bg->free_space_lock);
-	btrfs_put_block_group(dest_bg);
 
  	if (bg_needs_free_space) {
  		ret = btrfs_add_block_group_free_space(trans, dest_bg);
-		if (unlikely(ret))
+		if (unlikely(ret)) {

fs/btrfs/relocation.c static int move_existing_remap(struct btrfs_fs_info *fs_info, · line 4311

Quoted 10 lines
fs/btrfs/relocation.c +4 -0
+			btrfs_put_block_group(dest_bg);
  			goto end;
+		}
  	}
 
+	btrfs_put_block_group(dest_bg);
+
  	ret = btrfs_remove_from_free_space_tree(trans, dest_addr, dest_length);
  	if (unlikely(ret)) {
  		btrfs_remove_from_free_space_tree(trans, new_addr, dest_length);

Why can't you move the put to the end of the function and skip the new lookup of the BG further down the function?