Skip to contentSkip to conversation

fs: ext4: check on-disk indices before using them

PATCH RESEND Superseded Ana Bobillo 3 participants 16 messages Oct 25 – Oct 26 ext4 file system

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover fs: ext4: check on-disk indices before using them

This is a resend of the series posted on 23 October, now with the patches inline: the first posting carried them as attachments, which b4 and Patchwork cannot use. The patches are unchanged and still apply to master.

The ext4 driver takes several indices from the filesystem image and uses them without checking them against the structures they index. A corrupt or crafted image can then make ext4load read past an extent tree node, or make ext4write (and saveenv with the environment on ext4) write outside the block bitmaps, the inode bitmaps and the group descriptor table when it replaces an existing file.

This series checks each of those indices where it is read:

1. extent tree nodes: entry count against the node's capacity, and the depth, as Linux does
2. the triple indirect lookup compares the cached block with the wrong index, read past the end of its buffer
3. the write path refuses block group layouts its bitmap code cannot handle, including zero blocks per group, which divides by zero
4. block numbers released by the delete path must lie inside the filesystem
5. the block group of an inode is (n - 1) / inodes_per_group in the write path too, and inode numbers from directory entries are range checked
6. tests in test/py for the cases above

With sandbox_defconfig and CONFIG_ASAN, the new tests fail on master and pass with the series applied. On master the corrupt extent header is not rejected, ASan reports segfaults in ext4fs_reset_block_bmap() and in ext4fs_reset_inode_bmap(), and ext4fs_init() divides by zero. The existing ext4, env and mmc tests still pass, and repeatedly overwriting files on clean images, with and without extents, with 1 KiB and 4 KiB blocks, keeps the images clean for e2fsck.

Simon Glass's "ext4: Add a few overflow checks in the writing code" series from last year checks the block size and the table sizes in ext4fs_get_bgdtable() and ext4fs_init(). This series checks other fields; patch 3 adds its check next to his at the start of ext4fs_init(), so whichever lands second needs a small rebase.

Ana Bobillo (6):
fs: ext4: check extent tree nodes before walking them
fs: ext4: fix the triple indirect cache check in
read_allocated_block()
fs: ext4: refuse to write with an unsupported block group layout
fs: ext4: check block numbers before releasing them
fs: ext4: fix the block group of an inode in the write path
test: fs: ext4: add tests for corrupt on-disk indices

 fs/ext4/ext4_common.c                 |  54 +++++++-
 fs/ext4/ext4_write.c                  | 172 ++++++++++++++++----------
 include/ext4fs.h                      |   1 +
 scripts/pylint.base                   |   1 +
 test/py/tests/test_fs/test_ext_oob.py | 147 ++++++++++++++++++++++
 5 files changed, 306 insertions(+), 69 deletions(-)
 create mode 100644 test/py/tests/test_fs/test_ext_oob.py

base-commit: acc808479730e13e74199119eb9b2b9113999244

#1 lore raw

PATCH RESEND 1/6 fs: ext4: check extent tree nodes before walking them

From: Ana Bobillo <[email protected]>

ext4fs_get_extent_block() walks the extent tree of an inode using the eh_entries, eh_max and eh_depth fields of each node as found on disk, checking nothing but the magic number. read_allocated_block() then scans eh_entries extents of the leaf it returns.

A node can claim more entries than it can hold: up to 4 in the 60-byte i_block area of the inode, (blocksize - 12) / 12 in a tree block. Both loops then read past the end of the node, into the rest of the inode or past the cache buffer. An index node can also point back at itself or at any node of the same or a greater depth, so the walk never ends.

Check each node as Linux __ext4_ext_check() does: eh_max is non-zero and fits in the node, eh_entries does not exceed eh_max, the depth drops by exactly one at each level and an index node has at least one entry; and, as ext4_find_extent() requires, the depth is at most 5. A node that fails is reported as an invalid extent block, the error read_allocated_block() already returns for a bad magic number.

---
 fs/ext4/ext4_common.c | 42 +++++++++++++++++++++++++++++++++++++++++-
 include/ext4fs.h      |  1 +
 2 files changed, 42 insertions(+), 1 deletion(-)
fs/ext4/ext4_common.c +41 -1
index 9e1d574e5b1..3aab1c87233 100644
@@ -1529,6 +1529,38 @@ void ext4fs_allocate_blocks(struct ext2_inode *file_inode,
 
 #endif
 
+/**
+ * ext4fs_check_extent_header() - check an extent tree node before using it
+ *
+ * Some of the checks of Linux __ext4_ext_check() and ext4_find_extent(): the
+ * node must not claim more entries than fit in it, and the depth must be at
+ * most 5 and drop by one at each level, so that a corrupt node can neither be
+ * walked past its end nor make the tree loop.
+ *
+ * @eh:		extent header of the node
+ * @max:	number of entries that fit in the node
+ * @depth:	depth this node must have, or -1 for the root in the inode
+ * Return:	0 if the node is valid, -EINVAL otherwise
+ */
+static int ext4fs_check_extent_header(struct ext4_extent_header *eh, int max,
+				      int depth)
+{
+	if (le16_to_cpu(eh->eh_magic) != EXT4_EXT_MAGIC)
+		return -EINVAL;
+	if (!eh->eh_max || le16_to_cpu(eh->eh_max) > max)
+		return -EINVAL;
+	if (le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))
+		return -EINVAL;
+	if (le16_to_cpu(eh->eh_depth) > EXT4_MAX_EXTENT_DEPTH)
+		return -EINVAL;
+	if (depth >= 0 && le16_to_cpu(eh->eh_depth) != depth)
+		return -EINVAL;
+	if (eh->eh_depth && !eh->eh_entries)
+		return -EINVAL;
+
+	return 0;
+}
+
 static struct ext4_extent_header *ext4fs_get_extent_block
 	(struct ext2_data *data, struct ext_block_cache *cache,
 		struct ext4_extent_header *ext_block,
@@ -1537,16 +1569,24 @@ static struct ext4_extent_header *ext4fs_get_extent_block
 	struct ext4_extent_idx *index;
 	unsigned long long block;
 	int blksz = EXT2_BLOCK_SIZE(data);
+	/* The root node is held in the inode's 60-byte i_block area */
+	int max = (sizeof(((struct ext2_inode *)0)->b) -
+		   sizeof(struct ext4_extent_header)) /
+		  sizeof(struct ext4_extent);
+	int depth = -1;
 	int i;
 
 	while (1) {
 		index = (struct ext4_extent_idx *)(ext_block + 1);
 
-		if (le16_to_cpu(ext_block->eh_magic) != EXT4_EXT_MAGIC)
+		if (ext4fs_check_extent_header(ext_block, max, depth))
 			return NULL;
 
 		if (ext_block->eh_depth == 0)
 			return ext_block;
+		depth = le16_to_cpu(ext_block->eh_depth) - 1;
+		max = (blksz - sizeof(struct ext4_extent_header)) /
+		      sizeof(struct ext4_extent);
 		i = -1;
 		do {
 			i++;
include/ext4fs.h +1 -0
index fe3fb301ec8..19eda150cb6 100644
@@ -35,6 +35,7 @@ struct disk_partition;
 #define EXT4_TOPDIR_FL		0x00020000 /* Top of directory hierarchies*/
 #define EXT4_EXTENTS_FL		0x00080000 /* Inode uses extents */
 #define EXT4_EXT_MAGIC			0xf30a
+#define EXT4_MAX_EXTENT_DEPTH		5
 
 #define EXT4_FEATURE_RO_COMPAT_SPARSE_SUPER  0x0001
 #define EXT4_FEATURE_RO_COMPAT_LARGE_FILE    0x0002
Reviewed-by on v1 1/6
#2 lore raw

Re: [PATCH RESEND 1/6] fs: ext4: check extent tree nodes before walking them

Quoted 21 lines · Ana Bobillo

fs: ext4: check extent tree nodes before walking them

ext4fs_get_extent_block() walks the extent tree of an inode using the eh_entries, eh_max and eh_depth fields of each node as found on disk, checking nothing but the magic number. read_allocated_block() then scans eh_entries extents of the leaf it returns.

A node can claim more entries than it can hold: up to 4 in the 60-byte i_block area of the inode, (blocksize - 12) / 12 in a tree block. Both loops then read past the end of the node, into the rest of the inode or past the cache buffer. An index node can also point back at itself or at any node of the same or a greater depth, so the walk never ends.

Check each node as Linux __ext4_ext_check() does: eh_max is non-zero and fits in the node, eh_entries does not exceed eh_max, the depth drops by exactly one at each level and an index node has at least one entry; and, as ext4_find_extent() requires, the depth is at most 5. A node that fails is reported as an invalid extent block, the error read_allocated_block() already returns for a bad magic number.

Quoted 5 lines
 fs/ext4/ext4_common.c | 42 +++++++++++++++++++++++++++++++++++++++++-
 include/ext4fs.h      |  1 +
 2 files changed, 42 insertions(+), 1 deletion(-)
#3 lore raw

PATCH RESEND 2/6 fs: ext4: fix the triple indirect cache check in read_allocated_block()

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

In the triple indirect branch, read_allocated_block() reads the third level block from ext4fs_indir2_block[(rblock / perblock_child) % (blksz / 4)] and records it in ext4fs_indir3_blkno, but it decides whether that cached block can be reused by comparing against ext4fs_indir2_block[rblock / perblock_child], without the modulo.

For a file block reached through the second or a later entry of the triple indirect block (rblock >= (blksz / 4) * (blksz / 4)), rblock / perblock_child is at least blksz / 4, so the compare reads past the end of the blksz-byte ext4fs_indir2_block buffer and can make the lookup reuse the wrong cached block.

Use the same index for the compare as for the read.

---
 fs/ext4/ext4_common.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
fs/ext4/ext4_common.c +3 -3
index 3aab1c87233..cff112fb99b 100644
@@ -2008,9 +2008,9 @@ long int read_allocated_block(struct ext2_inode *inode, int fileblock,
 			}
 			ext4fs_indir3_size = blksz;
 		}
-		if ((le32_to_cpu(ext4fs_indir2_block[rblock
-						       /
-						       perblock_child]) <<
+		if ((le32_to_cpu(ext4fs_indir2_block[(rblock /
+						      perblock_child) %
+						     (blksz / 4)]) <<
 		     log2_blksz) != ext4fs_indir3_blkno) {
 			status =
 			    ext4fs_devread((lbaint_t)le32_to_cpu
Reviewed-by on v1 2/6
#4 lore raw

Re: [PATCH RESEND 2/6] fs: ext4: fix the triple indirect cache check in read_allocated_block()

Quoted 14 lines · Ana Bobillo

fs: ext4: fix the triple indirect cache check in read_allocated_block()

In the triple indirect branch, read_allocated_block() reads the third level block from ext4fs_indir2_block[(rblock / perblock_child) % (blksz / 4)] and records it in ext4fs_indir3_blkno, but it decides whether that cached block can be reused by comparing against ext4fs_indir2_block[rblock / perblock_child], without the modulo.

For a file block reached through the second or a later entry of the triple indirect block (rblock >= (blksz / 4) * (blksz / 4)), rblock / perblock_child is at least blksz / 4, so the compare reads past the end of the blksz-byte ext4fs_indir2_block buffer and can make the lookup reuse the wrong cached block.

Quoted 6 lines

Use the same index for the compare as for the read.

 fs/ext4/ext4_common.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
#5 lore raw

PATCH RESEND 3/6 fs: ext4: refuse to write with an unsupported block group layout

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

ext4fs_init() divides by s_blocks_per_group from the superblock to count the block groups, so a value of zero crashes the write path at once. The bitmap code of the write path also assumes one bitmap block's worth of blocks per group: ext4fs_set_block_bmap() and ext4fs_reset_block_bmap() find the bits of group n at n * blocksize bytes into its bitmap, and ext4fs_get_new_blk_no() numbers the blocks of group n from n * blocksize * 8. With any other s_blocks_per_group the groups after the first are indexed outside their bitmap buffers. s_inodes_per_group likewise cannot exceed the bits of one bitmap block.

mke2fs uses that layout unless it is told otherwise; it lowers s_blocks_per_group for 64 KiB blocks, with -g, or when many inodes are asked for. Check the layout at the start of ext4fs_init(), before the journal is replayed, and refuse to write to a filesystem of more than one group laid out any other way, instead of dividing by zero or indexing outside the bitmap buffers. A filesystem of a single group is still written to, as before.

---
 fs/ext4/ext4_write.c | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)
fs/ext4/ext4_write.c +19 -0
index 2fba2197c19..4e8fa434409 100644
@@ -605,11 +605,30 @@ int ext4fs_init(void)
 	int i;
 	uint32_t real_free_blocks = 0;
 	struct ext_filesystem *fs = get_fs();
+	struct ext2_sblock *sblock = &ext4fs_root->sblock;
+	uint32_t blk_per_grp = le32_to_cpu(sblock->blocks_per_group);
+	uint32_t inode_per_grp = le32_to_cpu(sblock->inodes_per_group);
 
 	/* populate fs */
 	fs->blksz = EXT2_BLOCK_SIZE(ext4fs_root);
 	fs->sect_perblk = fs->blksz >> fs->dev_desc->log2blksz;
 
+	/*
+	 * The bitmap code finds the bitmap bits of group n at n * blocksize
+	 * bytes, so every group must hold one bitmap block's worth of
+	 * blocks, unless there is only one group. Check this before the
+	 * journal is replayed, so that nothing is written to a filesystem
+	 * that is refused.
+	 */
+	if (!blk_per_grp || blk_per_grp > fs->blksz * 8 ||
+	    (blk_per_grp != fs->blksz * 8 &&
+	     le32_to_cpu(sblock->total_blocks) -
+	     le32_to_cpu(sblock->first_data_block) > blk_per_grp) ||
+	    !inode_per_grp || inode_per_grp > fs->blksz * 8) {
+		log_err("Unsupported block group layout, not writing\n");
+		return -EINVAL;
+	}
+
 	/* get the superblock */
 	fs->sb = zalloc(SUPERBLOCK_SIZE);
 	if (!fs->sb)
Reviewed-by on v1 3/6
#6 lore raw

Re: [PATCH RESEND 3/6] fs: ext4: refuse to write with an unsupported block group layout

Quoted 20 lines · Ana Bobillo

fs: ext4: refuse to write with an unsupported block group layout

ext4fs_init() divides by s_blocks_per_group from the superblock to count the block groups, so a value of zero crashes the write path at once. The bitmap code of the write path also assumes one bitmap block's worth of blocks per group: ext4fs_set_block_bmap() and ext4fs_reset_block_bmap() find the bits of group n at n * blocksize bytes into its bitmap, and ext4fs_get_new_blk_no() numbers the blocks of group n from n * blocksize * 8. With any other s_blocks_per_group the groups after the first are indexed outside their bitmap buffers. s_inodes_per_group likewise cannot exceed the bits of one bitmap block.

mke2fs uses that layout unless it is told otherwise; it lowers s_blocks_per_group for 64 KiB blocks, with -g, or when many inodes are asked for. Check the layout at the start of ext4fs_init(), before the journal is replayed, and refuse to write to a filesystem of more than one group laid out any other way, instead of dividing by zero or indexing outside the bitmap buffers. A filesystem of a single group is still written to, as before.

Quoted 4 lines
 fs/ext4/ext4_write.c | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)
#7 lore raw

PATCH RESEND 4/6 fs: ext4: check block numbers before releasing them

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

When ext4fs_write() replaces an existing file, ext4fs_delete_file() releases the file's blocks: the data blocks found by read_allocated_block() and, for a file using indirect blocks, the blocks listed in its indirect blocks. Each block number comes from the inode or from an indirect block on disk and is turned into a block group index used for fs->blk_bmaps[] and ext4fs_get_group_descriptor() without any check. A block number past the end of the filesystem makes ext4fs_reset_block_bmap() and ext4fs_bg_free_blocks_inc() write outside the bitmap array and the group descriptor table.

Add ext4fs_blk_to_group(), which computes the block group as ext4fs_get_new_blk_no() does, but only for a block inside the filesystem, and use it wherever the delete path computes the block group of a block. Make the delete_*_indirect_block() helpers return an error, so that ext4fs_delete_file() stops rather than releasing blocks of a corrupt inode; their out-of-memory, read and journal errors, which used to be ignored, now stop the delete as well.

---
 fs/ext4/ext4_write.c | 137 ++++++++++++++++++++++++-------------------
 1 file changed, 78 insertions(+), 59 deletions(-)
fs/ext4/ext4_write.c +78 -59
index 4e8fa434409..dc37ae1448d 100644
@@ -140,32 +140,62 @@ fail:
 	return -1;
 }
 
-static void delete_single_indirect_block(struct ext2_inode *inode)
+/**
+ * ext4fs_blk_to_group() - get the block group of a block to be released
+ *
+ * The block numbers come from the inode being deleted and from its indirect
+ * blocks, so check that they are inside the filesystem before they are used
+ * to index the block bitmaps and group descriptors. The group is computed
+ * as ext4fs_get_new_blk_no() does.
+ *
+ * @fs:		filesystem
+ * @blknr:	block number
+ * Return:	block group of @blknr, or -EINVAL if it is outside the filesystem
+ */
+static int ext4fs_blk_to_group(struct ext_filesystem *fs, uint64_t blknr)
+{
+	uint32_t blk_per_grp = le32_to_cpu(ext4fs_root->sblock.blocks_per_group);
+	uint32_t bg_idx;
+
+	if (blknr <= le32_to_cpu(ext4fs_root->sblock.first_data_block) ||
+	    blknr >= le32_to_cpu(ext4fs_root->sblock.total_blocks))
+		goto err;
+
+	/* blknr is below total_blocks, so it fits in 32 bits */
+	bg_idx = (uint32_t)blknr / blk_per_grp;
+	if (fs->blksz == 1024 && !((uint32_t)blknr % blk_per_grp))
+		bg_idx--;
+	if (bg_idx >= fs->no_blkgrp)
+		goto err;
+
+	return bg_idx;
+err:
+	printf("Invalid block number %llu\n", (unsigned long long)blknr);
+	return -EINVAL;
+}
+
+static int delete_single_indirect_block(struct ext2_inode *inode)
 {
 	struct ext2_block_group *bgd = NULL;
 	static int prev_bg_bmap_idx = -1;
 	uint32_t blknr;
-	int remainder;
 	int bg_idx;
 	int status;
-	uint32_t blk_per_grp = le32_to_cpu(ext4fs_root->sblock.blocks_per_group);
+	int ret = -1;
 	struct ext_filesystem *fs = get_fs();
 	char *journal_buffer = zalloc(fs->blksz);
 	if (!journal_buffer) {
 		printf("No memory\n");
-		return;
+		return -ENOMEM;
 	}
 
 	/* deleting the single indirect block associated with inode */
 	if (inode->b.blocks.indir_block != 0) {
 		blknr = le32_to_cpu(inode->b.blocks.indir_block);
 		debug("SIPB releasing %u\n", blknr);
-		bg_idx = blknr / blk_per_grp;
-		if (fs->blksz == 1024) {
-			remainder = blknr % blk_per_grp;
-			if (!remainder)
-				bg_idx--;
-		}
+		bg_idx = ext4fs_blk_to_group(fs, blknr);
+		if (bg_idx < 0)
+			goto fail;
 		ext4fs_reset_block_bmap(blknr, fs->blk_bmaps[bg_idx], bg_idx);
 		/* get  block group descriptor table */
 		bgd = ext4fs_get_group_descriptor(fs, bg_idx);
@@ -184,19 +214,21 @@ static void delete_single_indirect_block(struct ext2_inode *inode)
 			prev_bg_bmap_idx = bg_idx;
 		}
 	}
+	ret = 0;
 fail:
 	free(journal_buffer);
+
+	return ret;
 }
 
-static void delete_double_indirect_block(struct ext2_inode *inode)
+static int delete_double_indirect_block(struct ext2_inode *inode)
 {
 	int i;
 	short status;
 	static int prev_bg_bmap_idx = -1;
 	uint32_t blknr;
-	int remainder;
 	int bg_idx;
-	uint32_t blk_per_grp = le32_to_cpu(ext4fs_root->sblock.blocks_per_group);
+	int ret = -1;
 	__le32 *di_buffer = NULL;
 	void *dib_start_addr = NULL;
 	struct ext2_block_group *bgd = NULL;
@@ -204,7 +236,7 @@ static void delete_double_indirect_block(struct ext2_inode *inode)
 	char *journal_buffer = zalloc(fs->blksz);
 	if (!journal_buffer) {
 		printf("No memory\n");
-		return;
+		return -ENOMEM;
 	}
 
 	if (inode->b.blocks.double_indir_block != 0) {
@@ -222,12 +254,9 @@ static void delete_double_indirect_block(struct ext2_inode *inode)
 				break;
 
 			debug("DICB releasing %u\n", *di_buffer);
-			bg_idx = le32_to_cpu(*di_buffer) / blk_per_grp;
-			if (fs->blksz == 1024) {
-				remainder = le32_to_cpu(*di_buffer) % blk_per_grp;
-				if (!remainder)
-					bg_idx--;
-			}
+			bg_idx = ext4fs_blk_to_group(fs, le32_to_cpu(*di_buffer));
+			if (bg_idx < 0)
+				goto fail;
 			/* get  block group descriptor table */
 			bgd = ext4fs_get_group_descriptor(fs, bg_idx);
 			ext4fs_reset_block_bmap(le32_to_cpu(*di_buffer),
@@ -255,12 +284,9 @@ static void delete_double_indirect_block(struct ext2_inode *inode)
 
 		/* removing the parent double indirect block */
 		blknr = le32_to_cpu(inode->b.blocks.double_indir_block);
-		bg_idx = blknr / blk_per_grp;
-		if (fs->blksz == 1024) {
-			remainder = blknr % blk_per_grp;
-			if (!remainder)
-				bg_idx--;
-		}
+		bg_idx = ext4fs_blk_to_group(fs, blknr);
+		if (bg_idx < 0)
+			goto fail;
 		/* get  block group descriptor table */
 		bgd = ext4fs_get_group_descriptor(fs, bg_idx);
 		ext4fs_reset_block_bmap(blknr, fs->blk_bmaps[bg_idx], bg_idx);
@@ -280,20 +306,22 @@ static void delete_double_indirect_block(struct ext2_inode *inode)
 		}
 		debug("DIPB releasing %d\n", blknr);
 	}
+	ret = 0;
 fail:
 	free(dib_start_addr);
 	free(journal_buffer);
+
+	return ret;
 }
 
-static void delete_triple_indirect_block(struct ext2_inode *inode)
+static int delete_triple_indirect_block(struct ext2_inode *inode)
 {
 	int i, j;
 	short status;
 	static int prev_bg_bmap_idx = -1;
 	uint32_t blknr;
-	int remainder;
 	int bg_idx;
-	uint32_t blk_per_grp = le32_to_cpu(ext4fs_root->sblock.blocks_per_group);
+	int ret = -1;
 	__le32 *tigp_buffer = NULL;
 	void *tib_start_addr = NULL;
 	__le32 *tip_buffer = NULL;
@@ -303,7 +331,7 @@ static void delete_triple_indirect_block(struct ext2_inode *inode)
 	char *journal_buffer = zalloc(fs->blksz);
 	if (!journal_buffer) {
 		printf("No memory\n");
-		return;
+		return -ENOMEM;
 	}
 
 	if (inode->b.blocks.triple_indir_block != 0) {
@@ -331,12 +359,10 @@ static void delete_triple_indirect_block(struct ext2_inode *inode)
 			for (j = 0; j < fs->blksz / sizeof(int); j++) {
 				if (le32_to_cpu(*tip_buffer) == 0)
 					break;
-				bg_idx = le32_to_cpu(*tip_buffer) / blk_per_grp;
-				if (fs->blksz == 1024) {
-					remainder = le32_to_cpu(*tip_buffer) % blk_per_grp;
-					if (!remainder)
-						bg_idx--;
-				}
+				bg_idx = ext4fs_blk_to_group(fs,
+							     le32_to_cpu(*tip_buffer));
+				if (bg_idx < 0)
+					goto fail;
 
 				ext4fs_reset_block_bmap(le32_to_cpu(*tip_buffer),
 							fs->blk_bmaps[bg_idx],
@@ -373,12 +399,9 @@ static void delete_triple_indirect_block(struct ext2_inode *inode)
 			 * removing the grand parent blocks
 			 * which is connected to inode
 			 */
-			bg_idx = le32_to_cpu(*tigp_buffer) / blk_per_grp;
-			if (fs->blksz == 1024) {
-				remainder = le32_to_cpu(*tigp_buffer) % blk_per_grp;
-				if (!remainder)
-					bg_idx--;
-			}
+			bg_idx = ext4fs_blk_to_group(fs, le32_to_cpu(*tigp_buffer));
+			if (bg_idx < 0)
+				goto fail;
 			ext4fs_reset_block_bmap(le32_to_cpu(*tigp_buffer),
 						fs->blk_bmaps[bg_idx], bg_idx);
 
@@ -408,12 +431,9 @@ static void delete_triple_indirect_block(struct ext2_inode *inode)
 
 		/* removing the grand parent triple indirect block */
 		blknr = le32_to_cpu(inode->b.blocks.triple_indir_block);
-		bg_idx = blknr / blk_per_grp;
-		if (fs->blksz == 1024) {
-			remainder = blknr % blk_per_grp;
-			if (!remainder)
-				bg_idx--;
-		}
+		bg_idx = ext4fs_blk_to_group(fs, blknr);
+		if (bg_idx < 0)
+			goto fail;
 		ext4fs_reset_block_bmap(blknr, fs->blk_bmaps[bg_idx], bg_idx);
 		/* get  block group descriptor table */
 		bgd = ext4fs_get_group_descriptor(fs, bg_idx);
@@ -433,10 +453,13 @@ static void delete_triple_indirect_block(struct ext2_inode *inode)
 		}
 		debug("tigp buffer itself releasing %d\n", blknr);
 	}
+	ret = 0;
 fail:
 	free(tib_start_addr);
 	free(tipb_start_addr);
 	free(journal_buffer);
+
+	return ret;
 }
 
 static int ext4fs_delete_file(int inodeno)
@@ -444,7 +467,6 @@ static int ext4fs_delete_file(int inodeno)
 	struct ext2_inode inode;
 	short status;
 	int i;
-	int remainder;
 	long int blknr;
 	int bg_idx;
 	int ibmap_idx;
@@ -456,7 +478,6 @@ static int ext4fs_delete_file(int inodeno)
 	unsigned int inodes_per_block;
 	uint32_t blkno;
 	unsigned int blkoff;
-	uint32_t blk_per_grp = le32_to_cpu(ext4fs_root->sblock.blocks_per_group);
 	uint32_t inode_per_grp = le32_to_cpu(ext4fs_root->sblock.inodes_per_group);
 	struct ext2_inode *inode_buffer = NULL;
 	struct ext2_block_group *bgd = NULL;
@@ -489,9 +510,10 @@ static int ext4fs_delete_file(int inodeno)
 				inode.b.blocks.dir_blocks;
 		debug("del: dep=%d entries=%d\n", eh->eh_depth, eh->eh_entries);
 	} else {
-		delete_single_indirect_block(&inode);
-		delete_double_indirect_block(&inode);
-		delete_triple_indirect_block(&inode);
+		if (delete_single_indirect_block(&inode) ||
+		    delete_double_indirect_block(&inode) ||
+		    delete_triple_indirect_block(&inode))
+			goto fail;
 	}
 
 	/* release data blocks */
@@ -501,12 +523,9 @@ static int ext4fs_delete_file(int inodeno)
 			continue;
 		if (blknr < 0)
 			goto fail;
-		bg_idx = blknr / blk_per_grp;
-		if (fs->blksz == 1024) {
-			remainder = blknr % blk_per_grp;
-			if (!remainder)
-				bg_idx--;
-		}
+		bg_idx = ext4fs_blk_to_group(fs, blknr);
+		if (bg_idx < 0)
+			goto fail;
 		ext4fs_reset_block_bmap(blknr, fs->blk_bmaps[bg_idx],
 					bg_idx);
 		debug("EXT4 Block releasing %ld: %d\n", blknr, bg_idx);
#8 lore raw

Re: [PATCH RESEND 4/6] fs: ext4: check block numbers before releasing them

Hi Ana,

Quoted 12 lines · Ana Bobillo

fs: ext4: check block numbers before releasing them

When ext4fs_write() replaces an existing file, ext4fs_delete_file() releases the file's blocks: the data blocks found by read_allocated_block() and, for a file using indirect blocks, the blocks listed in its indirect blocks. Each block number comes from the inode or from an indirect block on disk and is turned into a block group index used for fs->blk_bmaps[] and ext4fs_get_group_descriptor() without any check. A block number past the end of the filesystem makes ext4fs_reset_block_bmap() and ext4fs_bg_free_blocks_inc() write outside the bitmap array and the group descriptor table.

Quoted 7 lines

Add ext4fs_blk_to_group(), which computes the block group as ext4fs_get_new_blk_no() does, but only for a block inside the filesystem, and use it wherever the delete path computes the block group of a block. Make the delete_*_indirect_block() helpers return an error, so that ext4fs_delete_file() stops rather than releasing blocks of a corrupt inode; their out-of-memory, read and journal errors, which used to be ignored, now stop the delete as well.

Not quite. Only the bitmap-block reads for the journal stop the delete. The reads of the indirect blocks themselves are still
unchecked: the ext4fs_devread() of 'double_indir_block', 'triple_indir_block' and each '*tigp_buffer' block. If one fails, the buffer stays zeroed and the inner loop ends at once, so the parent block is released and the blocks it points to are leaked. Since a failure now just discards the in-memory changes (ext4fs_update() is never reached), please can you check those three reads as well, so the commit message is accurate?

fs/ext4/ext4_write.c fail: · line 143

Quoted 12 lines

[...]

 fs/ext4/ext4_write.c | 137 +++++++++++++++++++++++++++++----------------------
 1 file changed, 78 insertions(+), 59 deletions(-)
fs/ext4/ext4_write.c +4 -0
@@ -140,32 +140,62 @@ fail:
+	/* blknr is below total_blocks, so it fits in 32 bits */
+	bg_idx = (uint32_t)blknr / blk_per_grp;
+	if (fs->blksz == 1024 && !((uint32_t)blknr % blk_per_grp))
+		bg_idx--;

With 'first_data_block' already in hand, this is just (blknr - first_data_block) / blk_per_grp, as Linux does in ext4_get_group_no_and_offset(). It gives the same result for the usual 1 KiB and 4 KiB layouts and drops the 1 KiB special case, which is really a stand-in for first_data_block == 1 (it is wrong for a 1 KiB filesystem with first_data_block 0, e.g. with bigalloc). ext4fs_get_new_blk_no() could then use the helper too, perhaps as a follow-up. What do you think?

fs/ext4/ext4_write.c fail: · line 141

Quoted 5 lines
fs/ext4/ext4_write.c +2 -1
@@ -140,32 +140,62 @@ fail:
-static void delete_single_indirect_block(struct ext2_inode *inode)
+static int delete_single_indirect_block(struct ext2_inode *inode)
+	int ret = -1;

The helpers now return -ENOMEM, -EINVAL or a bare -1. It would be worth using -EIO for the read and journal failures so all three return proper error codes.

Regards,
Simon

#9 lore raw

PATCH RESEND 5/6 fs: ext4: fix the block group of an inode in the write path

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

Inode numbers start at 1, so the block group of inode n is (n - 1) / s_inodes_per_group, as ext4fs_read_inode() computes it. The write path computes n / s_inodes_per_group instead, in ext4fs_delete_file(), for the new and the parent inode in ext4fs_write(), and in ext4fs_get_new_inode_no(). For the last inode of a group this gives the next group: ext4fs_delete_file() then clears a bit in the byte before that group's inode bitmap and zeroes an inode in the wrong inode table, and for the last group of the filesystem the index is past the end of fs->inode_bmaps[] and the group descriptor table.

The inode numbers given to ext4fs_delete_file() and taken as the parent inode come from directory entries on disk, so also check that they fall inside the filesystem before using them.

---
 fs/ext4/ext4_common.c |  6 ++++--
 fs/ext4/ext4_write.c  | 16 ++++++++++++----
 2 files changed, 16 insertions(+), 6 deletions(-)
fs/ext4/ext4_common.c +4 -2
index cff112fb99b..beb64794a72 100644
@@ -1156,8 +1156,10 @@ int ext4fs_get_new_inode_no(void)
 	} else {
 restart:
 		fs->curr_inode_no++;
-		/* get the blockbitmap index respective to blockno */
-		ibmap_idx = fs->curr_inode_no / inodes_per_grp;
+		/* get the inode bitmap index respective to inode no */
+		ibmap_idx = (fs->curr_inode_no - 1) / inodes_per_grp;
+		if (ibmap_idx >= fs->no_blkgrp)
+			goto fail;
 		struct ext2_block_group *bgd =
 			ext4fs_get_group_descriptor(fs, ibmap_idx);
 		uint16_t bg_flags = ext4fs_bg_get_flags(bgd);
fs/ext4/ext4_write.c +12 -4
index dc37ae1448d..6bae559849a 100644
@@ -485,6 +485,10 @@ static int ext4fs_delete_file(int inodeno)
 	char *journal_buffer = zalloc(fs->blksz);
 	if (!journal_buffer)
 		return -ENOMEM;
+	if (inodeno < 1 || (inodeno - 1) / inode_per_grp >= fs->no_blkgrp) {
+		printf("Invalid inode number %d\n", inodeno);
+		goto fail;
+	}
 	status = ext4fs_read_inode(ext4fs_root, inodeno, &inode);
 	if (status == 0)
 		goto fail;
@@ -551,7 +555,7 @@ static int ext4fs_delete_file(int inodeno)
 	/* release inode */
 	/* from the inode no to blockno */
 	inodes_per_block = fs->blksz / fs->inodesz;
-	ibmap_idx = inodeno / inode_per_grp;
+	ibmap_idx = (inodeno - 1) / inode_per_grp;
 
 	/* get the block no */
 	inodeno--;
@@ -939,7 +943,9 @@ int ext4fs_write(const char *fname, const char *buffer,
 
 	inodes_per_block = fs->blksz / fs->inodesz;
 	parent_inodeno = ext4fs_get_parent_inode_num(fname, filename, F_FILE);
-	if (parent_inodeno == -1)
+	if (parent_inodeno < 1 ||
+	    (parent_inodeno - 1) / le32_to_cpu(sblock->inodes_per_group) >=
+	    fs->no_blkgrp)
 		goto fail;
 	if (ext4fs_iget(parent_inodeno, g_parent_inode))
 		goto fail;
@@ -1032,7 +1038,8 @@ int ext4fs_write(const char *fname, const char *buffer,
 	temp_ptr = zalloc(fs->blksz);
 	if (!temp_ptr)
 		goto fail;
-	ibmap_idx = inodeno / le32_to_cpu(ext4fs_root->sblock.inodes_per_group);
+	ibmap_idx = (inodeno - 1) /
+		    le32_to_cpu(ext4fs_root->sblock.inodes_per_group);
 	inodeno--;
 	bgd = ext4fs_get_group_descriptor(fs, ibmap_idx);
 	itable_blkno = ext4fs_bg_get_inode_table_id(bgd, fs) +
@@ -1053,7 +1060,8 @@ int ext4fs_write(const char *fname, const char *buffer,
 		/* FIXME: Deallocate data blocks */
 		goto fail;
 	}
-	ibmap_idx = parent_inodeno / le32_to_cpu(ext4fs_root->sblock.inodes_per_group);
+	ibmap_idx = (parent_inodeno - 1) /
+		    le32_to_cpu(ext4fs_root->sblock.inodes_per_group);
 	parent_inodeno--;
 	bgd = ext4fs_get_group_descriptor(fs, ibmap_idx);
 	parent_itable_blkno = ext4fs_bg_get_inode_table_id(bgd, fs) +
#10 lore raw

Re: [PATCH RESEND 5/6] fs: ext4: fix the block group of an inode in the write path

Hi Ana,

Quoted 25 lines · Ana Bobillo

fs: ext4: fix the block group of an inode in the write path

Inode numbers start at 1, so the block group of inode n is (n - 1) / s_inodes_per_group, as ext4fs_read_inode() computes it. The write path computes n / s_inodes_per_group instead, in ext4fs_delete_file(), for the new and the parent inode in ext4fs_write(), and in ext4fs_get_new_inode_no(). For the last inode of a group this gives the next group: ext4fs_delete_file() then clears a bit in the byte before that group's inode bitmap and zeroes an inode in the wrong inode table, and for the last group of the filesystem the index is past the end of fs->inode_bmaps[] and the group descriptor table.

The inode numbers given to ext4fs_delete_file() and taken as the parent inode come from directory entries on disk, so also check that they fall inside the filesystem before using them.

 fs/ext4/ext4_common.c |  6 ++++--
 fs/ext4/ext4_write.c  | 16 ++++++++++++----
 2 files changed, 16 insertions(+), 6 deletions(-)

fs/ext4/ext4_write.c static int ext4fs_delete_file(int inodeno) · line 488

Quoted 4 lines
fs/ext4/ext4_write.c +4 -0
@@ -485,6 +485,10 @@ static int ext4fs_delete_file(int inodeno)
+	if (inodeno < 1 || (inodeno - 1) / inode_per_grp >= fs->no_blkgrp) {
+		printf("Invalid inode number %d\n", inodeno);
+		goto fail;
+	}

The same range check is open-coded for the parent inode in ext4fs_write(), and (n - 1) / inodes_per_group now appears in four places. Please can you put this in a helper next to ext4fs_blk_to_group(), e.g. ext4fs_inode_to_group() returning the group or -EINVAL, and use it for the 'ibmap_idx' calculations too? That would also make the parent check print something, since at present it fails silently.

BTW Linux ext4_valid_inum() also rejects reserved inodes below 's_first_ino' (other than the root). As it stands, a directory entry pointing at the journal inode (8) passes this check, so overwriting that file releases the journal's blocks and zeroes its inode. This isn't a memory-safety problem so it could be a follow-up, but it would be worth considering while you are here.

Regards,
Simon

#11 lore raw

PATCH RESEND 6/6 test: fs: ext4: add tests for corrupt on-disk indices

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

Add tests that make a small ext4 image with mkfs.ext4, corrupt one on-disk field and check that U-Boot rejects the image and is still responsive afterwards:

- test_fs_ext_oob_extent_header: an extent header with more entries than the inode can hold must give "invalid extent block"
- test_fs_ext_oob_delete_block: replacing a file whose indirect block lies past the end of the filesystem must fail with "Invalid block number"
- test_fs_ext_oob_group_layout: writing to a filesystem with s_blocks_per_group of zero must be refused
- test_fs_ext_oob_delete_inode: replacing a file whose directory entry names an inode past the last block group must fail

---
 scripts/pylint.base                   |   1 +
 test/py/tests/test_fs/test_ext_oob.py | 147 ++++++++++++++++++++++++++
 2 files changed, 148 insertions(+)
 create mode 100644 test/py/tests/test_fs/test_ext_oob.py
scripts/pylint.base +1 -0
index bc39e2385a3..4c618e4d032 100644
@@ -50,6 +50,7 @@ test_tests_test_fs_fstest_helpers.py 4.29
 test_tests_test_fs_test_basic.py 1.90
 test_tests_test_fs_test_erofs.py 8.97
 test_tests_test_fs_test_ext.py 1.48
+test_tests_test_fs_test_ext_oob.py 8.00
 test_tests_test_fs_test_fs_cmd.py 8.00
 test_tests_test_fs_test_fs_fat.py 2.50
 test_tests_test_fs_test_mkdir.py 3.04
test/py/tests/test_fs/test_ext_oob.py new file +147 -0

147 lines not on this page · raw message

#12 lore raw

Re: [PATCH RESEND 6/6] test: fs: ext4: add tests for corrupt on-disk indices

Hi Ana,

Quoted 24 lines · Ana Bobillo

test: fs: ext4: add tests for corrupt on-disk indices

Add tests that make a small ext4 image with mkfs.ext4, corrupt one on-disk field and check that U-Boot rejects the image and is still responsive afterwards:

- test_fs_ext_oob_extent_header: an extent header with more entries than the inode can hold must give "invalid extent block"
- test_fs_ext_oob_delete_block: replacing a file whose indirect block lies past the end of the filesystem must fail with "Invalid block number"
- test_fs_ext_oob_group_layout: writing to a filesystem with s_blocks_per_group of zero must be refused
- test_fs_ext_oob_delete_inode: replacing a file whose directory entry names an inode past the last block group must fail

 scripts/pylint.base                   |   1 +
 test/py/tests/test_fs/test_ext_oob.py | 147 ++++++++++++++++++++++++++++++++++
 2 files changed, 148 insertions(+)

test/py/tests/test_fs/test_ext_oob.py line 2

Quoted 2 lines
test/py/tests/test_fs/test_ext_oob.py +2 -0
@@ -0,0 +1,147 @@
+Each test makes a small ext4 image with mkfs.ext4, corrupts one on-disk
+field with debugfs and checks that U-Boot rejects the image and is still

Two of the tests patch the image with struct rather than debugfs, so please can you adjust this.

test/py/tests/test_fs/test_ext_oob.py line 5

Quoted 7 lines
test/py/tests/test_fs/test_ext_oob.py +5 -0
@@ -0,0 +1,147 @@
+def victim_field(img, field):
+    """Read back an inode field of /victim with debugfs"""
+    out = check_output(['debugfs', '-R', 'stat victim', img],
+                       stderr=open(os.devnull, 'w')).decode()
+    return out if field in out else ''

This leaks the file handle, as does test_fs_ext_oob_delete_inode(). Please can you use stderr=DEVNULL from subprocess instead? Also, since the callers only want a truth value, it would be clearer to return 'field in out' and call it something like victim_has() instead.

test/py/tests/test_fs/test_ext_oob.py line 5

Quoted 7 lines
test/py/tests/test_fs/test_ext_oob.py +5 -0
@@ -0,0 +1,147 @@
+    ubman.run_command('host bind 0 %s' % img)
+    out = ubman.run_command('ext4load host 0:0 %x /victim' % ADDR)
+    assert 'invalid extent block' in out
+    assert 'alive' in ubman.run_command('echo alive')
+    os.remove(img)

If an assert fails, the image stays in the persistent-data directory and host 0 stays bound to it. This applies to all four tests. Please can you use try/finally (or a small fixture) so the image is always removed and the device unbound?

scripts/pylint.base test_tests_test_fs_fstest_helpers.py 4.29 · line 53

Quoted 6 lines
scripts/pylint.base +1 -0
@@ -50,6 +50,7 @@ test_tests_test_fs_fstest_helpers.py 4.29
 test_tests_test_fs_test_basic.py 1.90
 test_tests_test_fs_test_erofs.py 8.97
 test_tests_test_fs_test_ext.py 1.48
+test_tests_test_fs_test_ext_oob.py 8.00

It would be better for a new file to be close to 10 than to record a low baseline. Nearly all the warnings I see are about % formatting where an f-string would do, plus the two open(os.devnull) calls above, so it should be easy to fix.

BTW nothing here covers the depth checks in patch 1. A test for those would be good, perhaps as a follow-up.

Regards,
Simon

#13 lore raw
In reply to Ana Bobillo

Hi Ana,

Quoted 1 line · Ana Bobillo

6. tests in test/py for the cases above

Not quite. The tests cover patches 1, 3 and 4 and the range check in patch 5, but nothing covers the triple-indirect fix in patch 2 or the (n - 1) / inodes_per_group change itself (the last inode of a group). A sparse file reaching the second entry of the triple-indirect block would cover patch 2, and replacing a file whose inode is the last in group 0 would cover patch 5. Please can you add those or adjust the cover letter? A follow-up would be fine too.

Quoted 5 lines

Simon Glass's "ext4: Add a few overflow checks in the writing code" series from last year checks the block size and the table sizes in ext4fs_get_bgdtable() and ext4fs_init(). This series checks other fields; patch 3 adds its check next to his at the start of ext4fs_init(), so whichever lands second needs a small rebase.

Thanks for mentioning this. I'm happy for this one to go first and I'll rebase mine on top at some point. Or feel free to resend mine.

Patch 3 reports its error with log_err() while patches 4 and 5 use printf() for the same kind of message. The ext4 driver mostly uses printf(), so it would be worth picking one and using it across the series.

Regards,
Simon

#14 lore raw
Quoted 14 lines · Simon Glass

Hi Ana,

Quoted 1 line · Ana Bobillo

6. tests in test/py for the cases above

Not quite. The tests cover patches 1, 3 and 4 and the range check in patch 5, but nothing covers the triple-indirect fix in patch 2 or the (n - 1) / inodes_per_group change itself (the last inode of a group). A sparse file reaching the second entry of the triple-indirect block would cover patch 2, and replacing a file whose inode is the last in group 0 would cover patch 5. Please can you add those or adjust the cover letter? A follow-up would be fine too.

Quoted 8 lines
Quoted 5 lines

Simon Glass's "ext4: Add a few overflow checks in the writing code" series from last year checks the block size and the table sizes in ext4fs_get_bgdtable() and ext4fs_init(). This series checks other fields; patch 3 adds its check next to his at the start of ext4fs_init(), so whichever lands second needs a small rebase.

Thanks for mentioning this. I'm happy for this one to go first and I'll rebase mine on top at some point. Or feel free to resend mine.

Please don't re-send Simon's patch series, there were some as I recall fundamental problems with it and someone else should attempt to solve any functional problems on their own.

Signature · 1 line
Tom
#15 lore raw
In reply to Ana Bobillo
Quoted 26 lines · Ana Bobillo

This is a resend of the series posted on 23 October, now with the patches inline: the first posting carried them as attachments, which b4 and Patchwork cannot use. The patches are unchanged and still apply to master.

The ext4 driver takes several indices from the filesystem image and uses them without checking them against the structures they index. A corrupt or crafted image can then make ext4load read past an extent tree node, or make ext4write (and saveenv with the environment on ext4) write outside the block bitmaps, the inode bitmaps and the group descriptor table when it replaces an existing file.

This series checks each of those indices where it is read:

1. extent tree nodes: entry count against the node's capacity, and the depth, as Linux does
2. the triple indirect lookup compares the cached block with the wrong index, read past the end of its buffer
3. the write path refuses block group layouts its bitmap code cannot handle, including zero blocks per group, which divides by zero
4. block numbers released by the delete path must lie inside the filesystem
5. the block group of an inode is (n - 1) / inodes_per_group in the write path too, and inode numbers from directory entries are range checked
6. tests in test/py for the cases above

Quoted 7 lines

With sandbox_defconfig and CONFIG_ASAN, the new tests fail on master and pass with the series applied. On master the corrupt extent header is not rejected, ASan reports segfaults in ext4fs_reset_block_bmap() and in ext4fs_reset_inode_bmap(), and ext4fs_init() divides by zero. The existing ext4, env and mmc tests still pass, and repeatedly overwriting files on clean images, with and without extents, with 1 KiB and 4 KiB blocks, keeps the images clean for e2fsck.

It would be good to see the results of a CI run for this series (and this also applies to the other series you've posted) and we document how to trigger one in:
https://docs.u-boot-project.org/en/latest/develop/ci_testing.html
Thanks.

Signature · 1 line
Tom