fs: btrfs: fix out of bounds write
authorAlex Shumsky <alexthreed@gmail.com>
Tue, 18 Jun 2024 21:41:38 +0000 (00:41 +0300)
committerTom Rini <trini@konsulko.com>
Wed, 26 Jun 2024 15:55:53 +0000 (09:55 -0600)
Fix btrfs_read/read_and_truncate_page write out of bounds of destination
buffer. Old behavior break bootstd malloc'd buffers of exact file size.
Previously this OOB write have not been noticed because distroboot usually
read files into huge static memory areas.

Signed-off-by: Alex Shumsky <alexthreed@gmail.com>
Fixes: e342718 ("fs: btrfs: Implement btrfs_file_read()")
Reviewed-by: Qu Wenruo <wqu@suse.com>
fs/btrfs/inode.c

index 4691612..3998ffc 100644 (file)
@@ -640,7 +640,11 @@ static int read_and_truncate_page(struct btrfs_path *path,
        extent_type = btrfs_file_extent_type(leaf, fi);
        if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
                ret = btrfs_read_extent_inline(path, fi, buf);
-               memcpy(dest, buf + page_off, min(page_len, ret));
+               if (ret < 0) {
+                       free(buf);
+                       return ret;
+               }
+               memcpy(dest, buf + page_off, min3(page_len, ret, len));
                free(buf);
                return len;
        }
@@ -652,7 +656,7 @@ static int read_and_truncate_page(struct btrfs_path *path,
                free(buf);
                return ret;
        }
-       memcpy(dest, buf + page_off, page_len);
+       memcpy(dest, buf + page_off, min(page_len, len));
        free(buf);
        return len;
 }