Skip to contentSkip to conversation

fs/cramfs: bound decompression output to the destination size

PATCH New Dilip Mallavarapu 1 participant 1 message Nov 17 Cramfs filesystem

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 fs/cramfs: bound decompression output to the destination size

cramfs_uncompress_block() set stream.avail_out to a fixed 8192 bytes, unrelated to the destination buffer. cramfs_uncompress_link() sizes its buffer as malloc(size + 1) from the inode's declared size, so a crafted block that inflates beyond that size overflows the heap buffer with attacker-controlled content (CWE-787). The length check runs only after the data has been written.

Pass the remaining destination size down and use it as avail_out, so an over-long block fails decompression (Z_BUF_ERROR) instead of overflowing.

Reachable e.g. via cramfsls over a directory containing a symlink.

---
 fs/cramfs/cramfs.c         | 9 ++++++++-
 fs/cramfs/uncompress.c     | 4 ++--
 include/cramfs/cramfs_fs.h | 2 +-
 3 files changed, 11 insertions(+), 4 deletions(-)
fs/cramfs/cramfs.c +8 -1
index 22148ff8fe2..411e707528b 100644
@@ -211,13 +211,20 @@ static int cramfs_uncompress (unsigned long begin, unsigned long offset,
 	unsigned long curr_block = (CRAMFS_GET_OFFSET (inode) +
 				    (((CRAMFS_24 (inode->size)) +
 				      4095) >> 12)) << 2;
+	int inode_size = CRAMFS_24 (inode->size);
 	int size, total_size = 0;
 	int i;
 
 	cramfs_uncompress_init ();
 
-	for (i = 0; i < ((CRAMFS_24 (inode->size) + 4095) >> 12); i++) {
+	for (i = 0; i < ((inode_size + 4095) >> 12); i++) {
+		/*
+		 * Bound each block's decompressed output to the remaining
+		 * declared size. Otherwise a crafted block can inflate past
+		 * the destination buffer (which is sized from inode->size).
+		 */
 		size = cramfs_uncompress_block ((void *) loadoffset,
+						inode_size - total_size,
 						(void *) (begin + curr_block),
 						(CRAMFS_32 (block_ptrs[i]) -
 						 curr_block));
fs/cramfs/uncompress.c +2 -2
index 97af8cb2b4f..43ee5f7609c 100644
@@ -29,7 +29,7 @@
 static z_stream stream;
 
 /* Returns length of decompressed data. */
-int cramfs_uncompress_block (void *dst, void *src, int srclen)
+int cramfs_uncompress_block (void *dst, int dstlen, void *src, int srclen)
 {
 	int err;
 
@@ -39,7 +39,7 @@ int cramfs_uncompress_block (void *dst, void *src, int srclen)
 	stream.avail_in = srclen;
 
 	stream.next_out = dst;
-	stream.avail_out = 4096 * 2;
+	stream.avail_out = dstlen;
 
 	err = inflate (&stream, Z_FINISH);
 
include/cramfs/cramfs_fs.h +1 -1
index e0c14f04af5..02c4867386b 100644
@@ -93,7 +93,7 @@ struct cramfs_super {
 #define CRAMFS_SET_NAMELEN(x,y) ((x)->namelen = (y))
 
 /* Uncompression interfaces to the underlying zlib */
-int cramfs_uncompress_block(void *dst, void *src, int srclen);
+int cramfs_uncompress_block(void *dst, int dstlen, void *src, int srclen);
 int cramfs_uncompress_init(void);
 int cramfs_uncompress_exit(void);
 
Signature · 1 line
2.53.0