nilfs2: harden dsync recovery and readdir
cover nilfs2: harden dsync recovery and readdir
While reviewing fs/nilfs2 I found two robustness issues with corrupted (or malformed) filesystem images, both dating back to the initial merge of nilfs2:
Patch 1: roll-forward recovery replays dsync logs without checking that the designated inode is a regular file. A log entry naming a special inode leads nilfs_get_block() to an uninitialized bmap and an indirect call through uninitialized memory. With the patch, mount of such an image fails cleanly with -EIO.
Patch 2: nilfs_readdir() parses the directory folio at whatever offset llseek left in ctx->pos, without snapping it onto an entry boundary the way ext2's ext2_validate_entry() does. dir_emit() can then emit bytes from a bogus entry, reading past the end of the folio.
Both patches were tested against current mainline (arm64): each issue reproduces before and is resolved after, and a mount/list/create/write/ fsync/remount/read-back pass shows normal operation unaffected. This was initially reported through [email protected]; per Greg K.H. and Ryusuke Konishi it is being resubmitted here for normal public review. Reproducers (small Python scripts that generate the images) are available on request.
These patches were developed with AI assistance (Anthropic Claude) and manually reviewed and tested.
Jake Labelle (2):
nilfs2: reject non-regular inodes in dsync recovery
nilfs2: validate directory position after llseek in readdir
fs/nilfs2/dir.c | 27 +++++++++++++++++++++++++++ fs/nilfs2/recovery.c | 13 +++++++++++++ 2 files changed, 40 insertions(+)
Signature · 1 line
2.43.0
PATCH 1/2 nilfs2: reject non-regular inodes in dsync recovery
During roll-forward recovery, nilfs_recover_dsync_blocks() obtains the inode designated by fi_ino of a dsync log without checking its type. If a corrupted image designates a special inode (e.g. a device node) there, the inode's embedded bmap was never initialized:__nilfs_read_inode() calls nilfs_bmap_read() only for regular files, directories and symlinks. The subsequent nilfs_get_block() then dereferences the uninitialized bmap->b_ops and jumps through it, crashing the kernel or worse.
Only regular files have data blocks to recover; reject anything else before touching its block mapping.
--- fs/nilfs2/recovery.c | 13 +++++++++++++ 1 file changed, 13 insertions(+)
fs/nilfs2/recovery.c +13 -0
@@ -540,6 +540,19 @@ static int nilfs_recover_dsync_blocks(struct the_nilfs *nilfs, goto failed_inode; } +/* +* Only regular files have data blocks and an initialized +* bmap; a crafted image can reference a special inode here, +* whose i_bmap_data was never set up by __nilfs_read_inode(). +*/ +if (!S_ISREG (inode->i_mode)) { +nilfs_warn (sb, +"%s: ino=%lu is not a regular file" , + __func__, (unsigned long )rb->ino); + err = -EIO ; + goto failed_inode; + } + pos = rb->blkoff << inode->i_blkbits; err =block_write_begin (inode->i_mapping, pos, blocksize, &folio, nilfs_get_block);
Signature · 1 line
2.43.0
Ryusuke Konishi
maintainerRe: [PATCH 1/2] nilfs2: reject non-regular inodes in dsync recovery
Quoted 31 lines · Jake Labelle
During roll-forward recovery,
nilfs_recover_dsync_blocks()obtains the inode designated byfi_inoof a dsync log without checking its type. If a corrupted image designates a special inode (e.g. a device node) there, the inode's embedded bmap was never initialized:__nilfs_read_inode()callsnilfs_bmap_read()only for regular files, directories and symlinks. The subsequentnilfs_get_block()then dereferences the uninitializedbmap->b_opsand jumps through it, crashing the kernel or worse.Only regular files have data blocks to recover; reject anything else before touching its block mapping.
Fixes 0f3e1c7f23f8 ("nilfs2: recovery functions")Co-Authored-By Claude Mythos 5 <[email protected]>Signed-off-by Jake Labelle <[email protected]>--- fs/nilfs2/recovery.c | 13 +++++++++++++ 1 file changed, 13 insertions(+)fs/nilfs2/recovery.c +3
-0@@ -540,6 +540,19 @@ static int nilfs_recover_dsync_blocks(struct the_nilfs *nilfs, goto failed_inode; } +/* +* Only regular files have data blocks and an initialized +* bmap; a crafted image can reference a special inode here,
fs/nilfs2/recovery.c static int nilfs_recover_dsync_blocks(struct the_nilfs *nilfs, · line 555
Quoted 10 lines
fs/nilfs2/recovery.c +10
-0+* whose i_bmap_data was never set up by __nilfs_read_inode(). +*/ +if (!S_ISREG (inode->i_mode)) { +nilfs_warn (sb, +"%s: ino=%lu is not a regular file" , + __func__, (unsigned long )rb->ino); + err = -EIO ; + goto failed_inode; + } +
Hi Jake
Thanks for submitting the patch.
In nilfs2, regular files are not the only inode types that have data blocks and bmap; directories and symbolic links also have them.
Also, since dsync logs are checked with CRCs, this condition should almost never fail under normal operation, so please wrap it with unlikely() or !likely().
Therefore, please update the conditional check as follows:
if (!likely(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
S_ISLNK(inode->i_mode))) {The comment stating that only regular files have data blocks should also be corrected accordingly.
In addition, please update the warning message to reflect that other valid types are allowed - for example, something concise like:
nilfs_warn(sb, "%s: invalid inode type (ino=%lu, mode=0%o)",
__func__, (unsigned long)rb->ino, inode->i_mode);(Strictly speaking, the latest type of rb->ino is u64, and type conversion for the inode number is missing in this function, but keeping it as is here is convenient for backporting.)
Additionally, please return -EINVAL instead of -EIO. Since nilfs_recover_dsync_blocks() is called as part of the mount process, we use -EINVAL for filesystem format errors detected during mount to conform to the mount system call specification.
Thanks,
Ryusuke Konishi
Quoted 6 lines
fs/nilfs2/recovery.c +0
-1pos = rb->blkoff << inode->i_blkbits; err =block_write_begin (inode->i_mapping, pos, blocksize, &folio, nilfs_get_block); --2.43.0
PATCH 2/2 nilfs2: validate directory position after llseek in readdir
In reply to Jake Labellenilfs_readdir() uses ctx->pos, which userspace can set to an arbitrary value via llseek, as an offset into the directory folio and parses whatever bytes sit there as a directory entry. A position pointing into the middle of an entry -- or at unused bytes of a corrupted image that the page validator never inspected -- makes dir_emit() copy up to 255 (name_len) bytes from a bogus entry, possibly reading past the end of the folio and returning unrelated memory contents to userspace.
Snap unaligned positions onto a valid entry boundary by walking the rec_len chain from the chunk start before parsing, as ext2 does in ext2_validate_entry().
--- fs/nilfs2/dir.c | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+)
fs/nilfs2/dir.c +27 -0
@@ -231,6 +231,21 @@ static struct nilfs_dir_entry *nilfs_next_entry(struct nilfs_dir_entry *p) nilfs_rec_len_from_disk(p->rec_len)); } +static inline unsigned int +nilfs_validate_entry (char *base,unsigned int offset,unsigned int mask) +{ +struct nilfs_dir_entry *de = (struct nilfs_dir_entry *)(base + offset); +struct nilfs_dir_entry *p = + (struct nilfs_dir_entry *)(base + (offset & mask)); + +while ((char *)p < (char *)de) { +if (p->rec_len ==0 ) +break ; + p =nilfs_next_entry (p); + } +return offset_in_page (p); +} +static int nilfs_readdir (struct file *file,struct dir_context *ctx) {loff_t pos = ctx->pos;
@@ -254,6 +269,18 @@ static int nilfs_readdir(struct file *file, struct dir_context *ctx) ctx->pos +=PAGE_SIZE - offset;return -EIO ; } +/* +* ctx->pos comes from userspace via llseek and may point +* into the middle of an entry — or at unvalidated bytes of +* a crafted image. Snap it onto a real entry boundary +* before parsing, as ext2 does; otherwise dir_emit() copies +* name_len bytes from a fake entry, reading past the folio. +*/ +if (offset & (nilfs_chunk_size (inode) -1 )) { + offset =nilfs_validate_entry (kaddr, offset, + ~(nilfs_chunk_size (inode) -1 )); + ctx->pos = ((loff_t )n <<PAGE_SHIFT ) + offset; + } de = (struct nilfs_dir_entry *)(kaddr + offset); limit = kaddr +nilfs_last_byte (inode, n) -NILFS_DIR_REC_LEN (1 );
Signature · 1 line
2.43.0
Ryusuke Konishi
maintainerRe: [PATCH 2/2] nilfs2: validate directory position after llseek in readdir
Quoted 52 lines · Jake Labelle
nilfs_readdir()usesctx->pos, which userspace can set to an arbitrary value via llseek, as an offset into the directory folio and parses whatever bytes sit there as a directory entry. A position pointing into the middle of an entry -- or at unused bytes of a corrupted image that the page validator never inspected -- makesdir_emit()copy up to 255 (name_len) bytes from a bogus entry, possibly reading past the end of the folio and returning unrelated memory contents to userspace.Snap unaligned positions onto a valid entry boundary by walking the
rec_lenchain from the chunk start before parsing, as ext2 does inext2_validate_entry().Fixes 2ba466d74ed7 ("nilfs2: directory entry operations")Co-Authored-By Claude Mythos 5 <[email protected]>Signed-off-by Jake Labelle <[email protected]>--- fs/nilfs2/dir.c | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+)fs/nilfs2/dir.c +17
-0@@ -231,6 +231,21 @@ static struct nilfs_dir_entry *nilfs_next_entry(struct nilfs_dir_entry *p) nilfs_rec_len_from_disk(p->rec_len)); } +static inline unsigned int +nilfs_validate_entry (char *base,unsigned int offset,unsigned int mask) +{ +struct nilfs_dir_entry *de = (struct nilfs_dir_entry *)(base + offset); +struct nilfs_dir_entry *p = + (struct nilfs_dir_entry *)(base + (offset & mask)); + +while ((char *)p < (char *)de) { +if (p->rec_len ==0 ) +break ; + p =nilfs_next_entry (p); + } +return offset_in_page (p); +} +static int nilfs_readdir (struct file *file,struct dir_context *ctx) {loff_t pos = ctx->pos;@@ -254,6 +269,18 @@ static int nilfs_readdir(struct file *file, struct dir_context *ctx) ctx->pos +=PAGE_SIZE - offset;return -EIO ; } +/* +* ctx->pos comes from userspace via llseek and may point
fs/nilfs2/dir.c static int nilfs_readdir(struct file *file, struct dir_context *ctx) · line 283
Quoted 10 lines
fs/nilfs2/dir.c +10
-0+* into the middle of an entry — or at unvalidated bytes of +* a crafted image. Snap it onto a real entry boundary +* before parsing, as ext2 does; otherwise dir_emit() copies +* name_len bytes from a fake entry, reading past the folio. +*/ +if (offset & (nilfs_chunk_size (inode) -1 )) { + offset =nilfs_validate_entry (kaddr, offset, + ~(nilfs_chunk_size (inode) -1 )); + ctx->pos = ((loff_t )n <<PAGE_SHIFT ) + offset; + }
Hi Jake,
I understand your point that we need to handle file pointer misalignment caused by directory seeks.
However, since directory entries have variable record lengths based on name length as calculated by the NILFS_DIR_REC_LEN() macro, couldn't the pointer still land in the middle of an entry even if offset is on a chunk boundary calculated from nilfs_chunk_size()?
Shouldn't calling nilfs_validate_entry() be done only during the initial check (checking offset directly derived from ctx->pos) and when offset is not on a page boundary (i.e. offset == 0)?
Also, as a minor nitpick, instead of calling nilfs_chunk_size(inode) repeatedly, could you declare and set a local variable named chunk_size at the beginning of the function and use it? (Although the compiler probably optimizes it, doing so makes the code cleaner from a readability perspective.)
Thanks,
Ryusuke Konishi
Quoted 6 lines
fs/nilfs2/dir.c +0
-1de = (struct nilfs_dir_entry *)(kaddr + offset); limit = kaddr +nilfs_last_byte (inode, n) -NILFS_DIR_REC_LEN (1 ); --2.43.0
v2 cover nilfs2: harden dsync recovery and readdir
In reply to Jake LabelleHi Ryusuke,
Sorry for the late reply, busy getting the flu 😄. I've put your review comments from v1 into the changes below.
While reviewing fs/nilfs2 I found two robustness issues with corrupted (or malformed) filesystem images, both dating back to the initial merge of nilfs2:
Patch 1: roll-forward recovery replays dsync logs without checking that the designated inode is one of the types that actually have a bmap. A log entry naming some other inode type leads nilfs_get_block() to an uninitialized bmap and an indirect call through uninitialized memory. With the patch, mount of such an image fails cleanly with -EINVAL.
Patch 2: nilfs_readdir() parses the directory folio at whatever offset llseek left in ctx->pos, without snapping it onto an entry boundary the way ext2's ext2_validate_entry() does. dir_emit() can then emit bytes from a bogus entry, reading past the end of the folio.
Both patches were tested against current mainline (arm64): each issue reproduces before and is resolved after, and a mount/list/create/write/ fsync/remount/read-back pass shows normal operation unaffected. This was initially reported through [email protected]; per Greg K.H. and Ryusuke Konishi it is being resubmitted here for normal public review. Reproducers (small Python scripts that generate the images) are available on request.
These patches were developed with AI assistance (Anthropic Claude) and manually reviewed and tested.
Changes in v2 (per Ryusuke Konishi's review of v1):
- Patch 1: also accept S_ISDIR/S_ISLNK (not just S_ISREG), wrap the check in likely(), return -EINVAL instead of -EIO.
- Patch 2: hoist nilfs_chunk_size(inode) into a local chunk_size variable; expanded the comment on why chunk-aligned offsets are already trustworthy without a chain walk.
Jake Labelle (2):
nilfs2: reject non-regular inodes in dsync recovery
nilfs2: validate directory position after llseek in readdir
fs/nilfs2/dir.c | 33 +++++++++++++++++++++++++++++++++ fs/nilfs2/recovery.c | 17 +++++++++++++++++ 2 files changed, 50 insertions(+)
Signature · 1 line
2.43.0
PATCH v2 1/2 nilfs2: reject non-regular inodes in dsync recovery
During roll-forward recovery, nilfs_recover_dsync_blocks() obtains the inode designated by fi_ino of a dsync log without checking its type. If a corrupted image designates a special inode (e.g. a device node) there, the inode's embedded bmap was never initialized:__nilfs_read_inode() calls nilfs_bmap_read() only for regular files, directories and symlinks. The subsequent nilfs_get_block() then dereferences the uninitialized bmap->b_ops and jumps through it, crashing the kernel or worse.
Regular files, directories, and symlinks are the only inode types with data blocks to recover; reject anything else before touching its block mapping.
---
v2:
- Also accept S_ISDIR and S_ISLNK, not just S_ISREG -- directories and symlinks have an initialized bmap too, only the check was missing before (Ryusuke Konishi).
- Wrap the check in likely() since dsync log CRCs make it fail only on a corrupted/crafted image, never in normal operation (Ryusuke Konishi).
- Return -EINVAL instead of -EIO to match the mount(2) error convention used elsewhere for on-disk format errors detected during mount (Ryusuke Konishi).
- Reworded the warning and comment for the wider set of accepted types.
fs/nilfs2/recovery.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+)
fs/nilfs2/recovery.c +17 -0
@@ -540,6 +540,23 @@ static int nilfs_recover_dsync_blocks(struct the_nilfs *nilfs, goto failed_inode; } +/* +* Regular files, directories, and symlinks are the only +* inode types with data blocks and an initialized bmap; +* a crafted image can reference some other inode type +* here, whose i_bmap_data was never set up by +* __nilfs_read_inode(). +*/ +if (!likely (S_ISREG (inode->i_mode) ||S_ISDIR (inode->i_mode) || +S_ISLNK (inode->i_mode))) { +nilfs_warn (sb, +"%s: invalid inode type (ino=%lu, mode=0%o)" , + __func__, (unsigned long )rb->ino, + inode->i_mode); + err = -EINVAL ; + goto failed_inode; + } + pos = rb->blkoff << inode->i_blkbits; err =block_write_begin (inode->i_mapping, pos, blocksize, &folio, nilfs_get_block);
Signature · 1 line
2.43.0
PATCH v2 2/2 nilfs2: validate directory position after llseek in readdir
In reply to Jake Labellenilfs_readdir() uses ctx->pos, which userspace can set to an arbitrary value via llseek, as an offset into the directory folio and parses whatever bytes sit there as a directory entry. A position pointing into the middle of an entry -- or at unused bytes of a corrupted image that the page validator never inspected -- makes dir_emit() copy up to 255 (name_len) bytes from a bogus entry, possibly reading past the end of the folio and returning unrelated memory contents to userspace.
Snap unaligned positions onto a valid entry boundary by walking the rec_len chain from the chunk start before parsing, as ext2 does in ext2_validate_entry().
---
v2:
- Hoist the repeated nilfs_chunk_size(inode) calls into a local chunk_size variable, matching the existing style elsewhere in dir.c (Ryusuke Konishi).
- Expanded the comment to explain why re-validation is only ever reachable on the first page of the loop, and why any chunk-aligned offset -- not just offset 0 -- is already a trustworthy entry
boundary: no on-disk rec_len chain crosses a chunk boundary, so chunk alignment alone (regardless of the variable-length entries within a chunk) is sufficient without a chain walk; a walk is only needed to recover from a non-chunk-aligned offset (Ryusuke Konishi's question, answered on-list rather than in code).
fs/nilfs2/dir.c | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+)
fs/nilfs2/dir.c +34 -0
@@ -231,11 +231,27 @@ static struct nilfs_dir_entry *nilfs_next_entry(struct nilfs_dir_entry *p) nilfs_rec_len_from_disk(p->rec_len)); } +static inline unsigned int +nilfs_validate_entry (char *base,unsigned int offset,unsigned int mask) +{ +struct nilfs_dir_entry *de = (struct nilfs_dir_entry *)(base + offset); +struct nilfs_dir_entry *p = + (struct nilfs_dir_entry *)(base + (offset & mask)); + +while ((char *)p < (char *)de) { +if (p->rec_len ==0 ) +break ; + p =nilfs_next_entry (p); + } +return offset_in_page (p); +} +static int nilfs_readdir (struct file *file,struct dir_context *ctx) {loff_t pos = ctx->pos;struct inode *inode =file_inode (file);struct super_block *sb = inode->i_sb; +unsigned int chunk_size =nilfs_chunk_size (inode);unsigned int offset = pos & ~PAGE_MASK ;unsigned long n = pos >>PAGE_SHIFT ;unsigned long npages =dir_pages (inode);
@@ -254,6 +270,24 @@ static int nilfs_readdir(struct file *file, struct dir_context *ctx) ctx->pos +=PAGE_SIZE - offset;return -EIO ; } +/* +* ctx->pos comes from userspace via llseek and may point +* into the middle of an entry -- or at unvalidated bytes +* of a crafted image. offset is only nonzero here on the +* very first iteration (subsequent pages always start at +* offset 0, which -- like any chunk boundary -- is always +* a legitimate entry start, since no rec_len chain crosses +* a chunk boundary). Snap a non-chunk-aligned offset onto +* a real entry boundary by walking the chain from the +* enclosing chunk's start, as ext2 does; otherwise +* dir_emit() copies name_len bytes from a fake entry, +* reading past the end of the folio. +*/ +if (offset & (chunk_size -1 )) { + offset =nilfs_validate_entry (kaddr, offset, + ~(chunk_size -1 )); + ctx->pos = ((loff_t )n <<PAGE_SHIFT ) + offset; + } de = (struct nilfs_dir_entry *)(kaddr + offset); limit = kaddr +nilfs_last_byte (inode, n) -NILFS_DIR_REC_LEN (1 );
Signature · 1 line
2.43.0
Ryusuke Konishi
maintainerRe: [PATCH v2 2/2] nilfs2: validate directory position after llseek in readdir
Quoted 80 lines · Jake Labelle
nilfs_readdir()usesctx->pos, which userspace can set to an arbitrary value via llseek, as an offset into the directory folio and parses whatever bytes sit there as a directory entry. A position pointing into the middle of an entry -- or at unused bytes of a corrupted image that the page validator never inspected -- makesdir_emit()copy up to 255 (name_len) bytes from a bogus entry, possibly reading past the end of the folio and returning unrelated memory contents to userspace.Snap unaligned positions onto a valid entry boundary by walking the
rec_lenchain from the chunk start before parsing, as ext2 does inext2_validate_entry().Fixes 2ba466d74ed7 ("nilfs2: directory entry operations")Co-Authored-By Claude Mythos 5 <[email protected]>Signed-off-by Jake Labelle <[email protected]>---
v2:
- Hoist the repeatednilfs_chunk_size(inode)calls into a localchunk_sizevariable, matching the existing style elsewhere indir.c(Ryusuke Konishi).
- Expanded the comment to explain why re-validation is only ever reachable on the first page of the loop, and why any chunk-aligned offset -- not just offset 0 -- is already a trustworthy entry
boundary: no on-diskrec_lenchain crosses a chunk boundary, so chunk alignment alone (regardless of the variable-length entries within a chunk) is sufficient without a chain walk; a walk is only needed to recover from a non-chunk-aligned offset (Ryusuke Konishi's question, answered on-list rather than in code).fs/nilfs2/dir.c | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+)fs/nilfs2/dir.c +27
-0@@ -231,11 +231,27 @@ static struct nilfs_dir_entry *nilfs_next_entry(struct nilfs_dir_entry *p) nilfs_rec_len_from_disk(p->rec_len)); } +static inline unsigned int +nilfs_validate_entry (char *base,unsigned int offset,unsigned int mask) +{ +struct nilfs_dir_entry *de = (struct nilfs_dir_entry *)(base + offset); +struct nilfs_dir_entry *p = + (struct nilfs_dir_entry *)(base + (offset & mask)); + +while ((char *)p < (char *)de) { +if (p->rec_len ==0 ) +break ; + p =nilfs_next_entry (p); + } +return offset_in_page (p); +} +static int nilfs_readdir (struct file *file,struct dir_context *ctx) {loff_t pos = ctx->pos;struct inode *inode =file_inode (file);struct super_block *sb = inode->i_sb; +unsigned int chunk_size =nilfs_chunk_size (inode);unsigned int offset = pos & ~PAGE_MASK ;unsigned long n = pos >>PAGE_SHIFT ;unsigned long npages =dir_pages (inode);@@ -254,6 +270,24 @@ static int nilfs_readdir(struct file *file, struct dir_context *ctx) ctx->pos +=PAGE_SIZE - offset;return -EIO ; } +/* +* ctx->pos comes from userspace via llseek and may point +* into the middle of an entry -- or at unvalidated bytes +* of a crafted image. offset is only nonzero here on the +* very first iteration (subsequent pages always start at +* offset 0, which -- like any chunk boundary -- is always +* a legitimate entry start, since no rec_len chain crosses +* a chunk boundary). Snap a non-chunk-aligned offset onto +* a real entry boundary by walking the chain from the +* enclosing chunk's start, as ext2 does; otherwise +* dir_emit() copies name_len bytes from a fake entry,
fs/nilfs2/dir.c static int nilfs_readdir(struct file *file, struct dir_context *ctx) · line 293
Quoted 10 lines
fs/nilfs2/dir.c +7
-0+* reading past the end of the folio. +*/ +if (offset & (chunk_size -1 )) { + offset =nilfs_validate_entry (kaddr, offset, + ~(chunk_size -1 )); + ctx->pos = ((loff_t )n <<PAGE_SHIFT ) + offset; + } de = (struct nilfs_dir_entry *)(kaddr + offset); limit = kaddr +nilfs_last_byte (inode, n) -NILFS_DIR_REC_LEN (1 );
Hi Jake,
I ran some local tests with the v2 patch set and noticed a boundary issue when seeking into the middle of the last directory entry in a chunk/page.
When 'pos' points to an unaligned offset inside the last entry (for example, offset 19 inside '..' in an empty directory where 'rec_len' spans up to 4096):
1. nilfs_validate_entry() walks the 'rec_len' chain starting from offset 0.
2. 'p' advances past the last entry, so its address becomes 'base + chunk_size' (e.g. 'base + 4096').
3. The loop terminates, and the function evaluates offset_in_page(p).
When page size == chunk_size (such as standard 4KB block setups), offset_in_page(base + 4096) evaluates to 0 due to wrap-around. As a result, nilfs_readdir() resets 'offset' to 0 and re-emits '.' instead of reaching the end of the chunk or EOF.
Could you adjust this so that reaching the end of a chunk yields 'chunk_size' (including cases where 'chunk_size' equals 'PAGE_SIZE') rather than wrapping around to 0?
This could be handled either inside nilfs_validate_entry() or by detecting the wrap-around in the caller and rounding 'offset' up to 'chunk_size'.
Also, when revising the patches, could you update the AI attribution tags to use the "Assisted-by:" tag format as mentioned in my reply to the cover letter?
Thanks,
Ryusuke Konishi
Ryusuke Konishi
maintainerRe: [PATCH v2 2/2] nilfs2: validate directory position after llseek in readdir
Quoted 120 lines · Ryusuke Konishi
Quoted 80 lines · Jake Labelle
nilfs_readdir()usesctx->pos, which userspace can set to an arbitrary value via llseek, as an offset into the directory folio and parses whatever bytes sit there as a directory entry. A position pointing into the middle of an entry -- or at unused bytes of a corrupted image that the page validator never inspected -- makesdir_emit()copy up to 255 (name_len) bytes from a bogus entry, possibly reading past the end of the folio and returning unrelated memory contents to userspace.Snap unaligned positions onto a valid entry boundary by walking the
rec_lenchain from the chunk start before parsing, as ext2 does inext2_validate_entry().Fixes 2ba466d74ed7 ("nilfs2: directory entry operations")Co-Authored-By Claude Mythos 5 <[email protected]>Signed-off-by Jake Labelle <[email protected]>---
v2:
- Hoist the repeatednilfs_chunk_size(inode)calls into a localchunk_sizevariable, matching the existing style elsewhere indir.c(Ryusuke Konishi).
- Expanded the comment to explain why re-validation is only ever reachable on the first page of the loop, and why any chunk-aligned offset -- not just offset 0 -- is already a trustworthy entry
boundary: no on-diskrec_lenchain crosses a chunk boundary, so chunk alignment alone (regardless of the variable-length entries within a chunk) is sufficient without a chain walk; a walk is only needed to recover from a non-chunk-aligned offset (Ryusuke Konishi's question, answered on-list rather than in code).fs/nilfs2/dir.c | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+)fs/nilfs2/dir.c +27
-0@@ -231,11 +231,27 @@ static struct nilfs_dir_entry *nilfs_next_entry(struct nilfs_dir_entry *p) nilfs_rec_len_from_disk(p->rec_len)); } +static inline unsigned int +nilfs_validate_entry (char *base,unsigned int offset,unsigned int mask) +{ +struct nilfs_dir_entry *de = (struct nilfs_dir_entry *)(base + offset); +struct nilfs_dir_entry *p = + (struct nilfs_dir_entry *)(base + (offset & mask)); + +while ((char *)p < (char *)de) { +if (p->rec_len ==0 ) +break ; + p =nilfs_next_entry (p); + } +return offset_in_page (p); +} +static int nilfs_readdir (struct file *file,struct dir_context *ctx) {loff_t pos = ctx->pos;struct inode *inode =file_inode (file);struct super_block *sb = inode->i_sb; +unsigned int chunk_size =nilfs_chunk_size (inode);unsigned int offset = pos & ~PAGE_MASK ;unsigned long n = pos >>PAGE_SHIFT ;unsigned long npages =dir_pages (inode);@@ -254,6 +270,24 @@ static int nilfs_readdir(struct file *file, struct dir_context *ctx) ctx->pos +=PAGE_SIZE - offset;return -EIO ; } +/* +* ctx->pos comes from userspace via llseek and may point +* into the middle of an entry -- or at unvalidated bytes +* of a crafted image. offset is only nonzero here on the +* very first iteration (subsequent pages always start at +* offset 0, which -- like any chunk boundary -- is always +* a legitimate entry start, since no rec_len chain crosses +* a chunk boundary). Snap a non-chunk-aligned offset onto +* a real entry boundary by walking the chain from the +* enclosing chunk's start, as ext2 does; otherwise +* dir_emit() copies name_len bytes from a fake entry, fs/nilfs2/dir.c static int nilfs_readdir(struct file *file, struct dir_context *ctx) · line 293
Quoted 10 lines
fs/nilfs2/dir.c +7
-0+* reading past the end of the folio. +*/ +if (offset & (chunk_size -1 )) { + offset =nilfs_validate_entry (kaddr, offset, + ~(chunk_size -1 )); + ctx->pos = ((loff_t )n <<PAGE_SHIFT ) + offset; + } de = (struct nilfs_dir_entry *)(kaddr + offset); limit = kaddr +nilfs_last_byte (inode, n) -NILFS_DIR_REC_LEN (1 );Hi Jake,
I ran some local tests with the v2 patch set and noticed a boundary issue when seeking into the middle of the last directory entry in a chunk/page.
When 'pos' points to an unaligned offset inside the last entry (for example, offset 19 inside '..' in an empty directory where '
rec_len' spans up to 4096):1.
nilfs_validate_entry()walks the 'rec_len' chain starting from offset 0.
2. 'p' advances past the last entry, so its address becomes 'base +chunk_size' (e.g. 'base + 4096').
3. The loop terminates, and the function evaluatesoffset_in_page(p).When page size ==
chunk_size(such as standard 4KB block setups),offset_in_page(base + 4096)evaluates to 0 due to wrap-around. As a result,nilfs_readdir()resets 'offset' to 0 and re-emits '.' instead of reaching the end of the chunk or EOF.Could you adjust this so that reaching the end of a chunk yields '
chunk_size' (including cases where 'chunk_size' equals 'PAGE_SIZE') rather than wrapping around to 0?
This could be handled either insidenilfs_validate_entry()or by detecting the wrap-around in the caller and rounding 'offset' up to 'chunk_size'.
Quoted 6 lines
Also, when revising the patches, could you update the AI attribution tags to use the "Assisted-by:" tag format as mentioned in my reply to the cover letter?
Thanks,
Ryusuke Konishi
Hi Jake,
As a quick follow-up regarding nilfs_validate_entry(), I think it is better to change its return value calculation from:
return offset_in_page(p);
to:
return (char *)p - base;
If p reaches the page boundary (PAGE_SIZE), offset_in_page() wraps around to 0, which could cause unexpected behavior in the caller. Returning (char *)p - base avoids this wrap-around and yields chunk size properly, allowing the caller to safely terminate its loop via the boundary check.
What do you think?
Thanks,
Ryusuke Konishi
Ryusuke Konishi
maintainerRe: [PATCH v2 2/2] nilfs2: validate directory position after llseek in readdir
Quoted 145 lines · Ryusuke Konishi
Quoted 120 lines · Ryusuke Konishi
Quoted 80 lines · Jake Labelle
nilfs_readdir()usesctx->pos, which userspace can set to an arbitrary value via llseek, as an offset into the directory folio and parses whatever bytes sit there as a directory entry. A position pointing into the middle of an entry -- or at unused bytes of a corrupted image that the page validator never inspected -- makesdir_emit()copy up to 255 (name_len) bytes from a bogus entry, possibly reading past the end of the folio and returning unrelated memory contents to userspace.Snap unaligned positions onto a valid entry boundary by walking the
rec_lenchain from the chunk start before parsing, as ext2 does inext2_validate_entry().Fixes 2ba466d74ed7 ("nilfs2: directory entry operations")Co-Authored-By Claude Mythos 5 <[email protected]>Signed-off-by Jake Labelle <[email protected]>---
v2:
- Hoist the repeatednilfs_chunk_size(inode)calls into a localchunk_sizevariable, matching the existing style elsewhere indir.c(Ryusuke Konishi).
- Expanded the comment to explain why re-validation is only ever reachable on the first page of the loop, and why any chunk-aligned offset -- not just offset 0 -- is already a trustworthy entry
boundary: no on-diskrec_lenchain crosses a chunk boundary, so chunk alignment alone (regardless of the variable-length entries within a chunk) is sufficient without a chain walk; a walk is only needed to recover from a non-chunk-aligned offset (Ryusuke Konishi's question, answered on-list rather than in code).fs/nilfs2/dir.c | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+)fs/nilfs2/dir.c +27
-0@@ -231,11 +231,27 @@ static struct nilfs_dir_entry *nilfs_next_entry(struct nilfs_dir_entry *p) nilfs_rec_len_from_disk(p->rec_len)); } +static inline unsigned int +nilfs_validate_entry (char *base,unsigned int offset,unsigned int mask) +{ +struct nilfs_dir_entry *de = (struct nilfs_dir_entry *)(base + offset); +struct nilfs_dir_entry *p = + (struct nilfs_dir_entry *)(base + (offset & mask)); + +while ((char *)p < (char *)de) { +if (p->rec_len ==0 ) +break ; + p =nilfs_next_entry (p); + } +return offset_in_page (p); +} +static int nilfs_readdir (struct file *file,struct dir_context *ctx) {loff_t pos = ctx->pos;struct inode *inode =file_inode (file);struct super_block *sb = inode->i_sb; +unsigned int chunk_size =nilfs_chunk_size (inode);unsigned int offset = pos & ~PAGE_MASK ;unsigned long n = pos >>PAGE_SHIFT ;unsigned long npages =dir_pages (inode);@@ -254,6 +270,24 @@ static int nilfs_readdir(struct file *file, struct dir_context *ctx) ctx->pos +=PAGE_SIZE - offset;return -EIO ; } +/* +* ctx->pos comes from userspace via llseek and may point +* into the middle of an entry -- or at unvalidated bytes +* of a crafted image. offset is only nonzero here on the +* very first iteration (subsequent pages always start at +* offset 0, which -- like any chunk boundary -- is always +* a legitimate entry start, since no rec_len chain crosses +* a chunk boundary). Snap a non-chunk-aligned offset onto +* a real entry boundary by walking the chain from the +* enclosing chunk's start, as ext2 does; otherwise +* dir_emit() copies name_len bytes from a fake entry, fs/nilfs2/dir.c static int nilfs_readdir(struct file *file, struct dir_context *ctx) · line 293
Quoted 10 lines
fs/nilfs2/dir.c +7
-0+* reading past the end of the folio. +*/ +if (offset & (chunk_size -1 )) { + offset =nilfs_validate_entry (kaddr, offset, + ~(chunk_size -1 )); + ctx->pos = ((loff_t )n <<PAGE_SHIFT ) + offset; + } de = (struct nilfs_dir_entry *)(kaddr + offset); limit = kaddr +nilfs_last_byte (inode, n) -NILFS_DIR_REC_LEN (1 );Hi Jake,
I ran some local tests with the v2 patch set and noticed a boundary issue when seeking into the middle of the last directory entry in a chunk/page.
When 'pos' points to an unaligned offset inside the last entry (for example, offset 19 inside '..' in an empty directory where '
rec_len' spans up to 4096):1.
nilfs_validate_entry()walks the 'rec_len' chain starting from offset 0.
2. 'p' advances past the last entry, so its address becomes 'base +chunk_size' (e.g. 'base + 4096').
3. The loop terminates, and the function evaluatesoffset_in_page(p).When page size ==
chunk_size(such as standard 4KB block setups),offset_in_page(base + 4096)evaluates to 0 due to wrap-around. As a result,nilfs_readdir()resets 'offset' to 0 and re-emits '.' instead of reaching the end of the chunk or EOF.Could you adjust this so that reaching the end of a chunk yields '
chunk_size' (including cases where 'chunk_size' equals 'PAGE_SIZE') rather than wrapping around to 0?
This could be handled either insidenilfs_validate_entry()or by detecting the wrap-around in the caller and rounding 'offset' up to 'chunk_size'.Quoted 6 lines
Also, when revising the patches, could you update the AI attribution tags to use the "Assisted-by:" tag format as mentioned in my reply to the cover letter?
Thanks,
Ryusuke KonishiHi Jake,
As a quick follow-up regarding
nilfs_validate_entry(), I think it is better to change its return value calculation from:return offset_in_page(p);to:
return (char *)p - base;If p reaches the page boundary (
PAGE_SIZE),offset_in_page()wraps around to 0, which could cause unexpected behavior in the caller. Returning (char *)p - base avoids this wrap-around and yields chunk size properly, allowing the caller to safely terminate its loop via the boundary check.
Quoted 4 lines
What do you think?
Thanks,
Ryusuke Konishi
Hi Jake,
I have one additional piece of feedback regarding the commit message and code comment that I would like you to reflect in the patch set.
Looking closely at the commit description again, the statement:
"possibly reading past the end of the folio and returning unrelated memory contents to userspace."
appears to be inaccurate for the original nilfs_readdir() implementation.
Because the inner loop enforces '(char *)de <= limit' before processing any entry (where 'limit' is capped at 'nilfs_last_byte(inode, n) - NILFS_DIR_REC_LEN(1)'), an unaligned pointer that points past 'limit' fails this check and never enters the loop. Therefore, it cannot read past the end of the folio or leak out-of-bounds memory contents to userspace.
The actual issue is that an unaligned offset within the valid page boundary parses arbitrary bytes inside the folio as a valid 'nilfs_dir_entry', returning bogus/corrupted directory entries to userspace.
Could you update the commit message to reflect that the bug is parsing bogus entries within the folio, rather than out-of-bounds folio access?
Similarly, the last sentence of the comment added inside nilfs_readdir():
"otherwise dir_emit() copies name_len bytes from a fake entry, reading past the end of the folio."
also has the same inaccuracy. Could you update that sentence as well?
For example:
"otherwise dir_emit() copies name_len bytes from a fake entry, returning bogus directory entries to userspace."
Thanks,
Ryusuke Konishi
Ryusuke Konishi
maintainerRe: [PATCH v2 2/2] nilfs2: validate directory position after llseek in readdir
Quoted 34 lines · Ryusuke Konishi
Hi Jake,
I have one additional piece of feedback regarding the commit message and code comment that I would like you to reflect in the patch set.
Looking closely at the commit description again, the statement:
"possibly reading past the end of the folio and returning unrelated memory contents to userspace."
appears to be inaccurate for the original
nilfs_readdir()implementation.Because the inner loop enforces '(char *)de <= limit' before processing any entry (where 'limit' is capped at '
nilfs_last_byte(inode, n)-NILFS_DIR_REC_LEN(1)'), an unaligned pointer that points past 'limit' fails this check and never enters the loop. Therefore, it cannot read past the end of the folio or leak out-of-bounds memory contents to userspace.The actual issue is that an unaligned offset within the valid page boundary parses arbitrary bytes inside the folio as a valid '
nilfs_dir_entry', returning bogus/corrupted directory entries to userspace.Could you update the commit message to reflect that the bug is parsing bogus entries within the folio, rather than out-of-bounds folio access?
Similarly, the last sentence of the comment added inside
nilfs_readdir():"otherwise
dir_emit()copiesname_lenbytes from a fake entry, reading past the end of the folio."
Quoted 8 lines
also has the same inaccuracy. Could you update that sentence as well?
For example:"otherwise
dir_emit()copiesname_lenbytes from a fake entry, returning bogus directory entries to userspace."Thanks,
Ryusuke Konishi
Hi Jake,
Sorry for sending multiple emails in a row before hearing back from you, but I must retract my previous comment regarding the out-of-bounds access.
While dir_emit() and its underlying VFS actors (e.g. filldir/filldir64) are designed defensively, looking more closely at their implementation, the safeguard appears to be incomplete when dealing with a corrupted 'name_len' (whether that actually triggers a kernel bug or other issue in practice is unclear, but the point that an out-of-bounds page access could occur seems correct).
Even though 'de' itself satisfies the '(char *)de <= limit' check, an unaligned entry near the page boundary may have a bogus 'de->name_len' (for instance, 255).
The verify_dirent_name() helper inside the actor called by dir_emit() executes memchr() on 'de->name' for that length, which will read past the mapped page boundary.
So your original description about reading past the end of the page/folio is correct.
Please disregard my previous email about updating those statements in the commit message and code comment.
Sorry for any confusion caused!
Thanks,
Ryusuke Konishi
Ryusuke Konishi
maintainerQuoted 32 lines · Jake Labelle
Hi Ryusuke,
Sorry for the late reply, busy getting the flu 😄. I've put your review comments from v1 into the changes below.
While reviewing fs/nilfs2 I found two robustness issues with corrupted (or malformed) filesystem images, both dating back to the initial merge of nilfs2:
Patch 1: roll-forward recovery replays dsync logs without checking that the designated inode is one of the types that actually have a bmap. A log entry naming some other inode type leads
nilfs_get_block()to an uninitialized bmap and an indirect call through uninitialized memory. With the patch, mount of such an image fails cleanly with-EINVAL.Patch 2:
nilfs_readdir()parses the directory folio at whatever offset llseek left inctx->pos, without snapping it onto an entry boundary the way ext2'sext2_validate_entry()does.dir_emit()can then emit bytes from a bogus entry, reading past the end of the folio.Both patches were tested against current mainline (arm64): each issue reproduces before and is resolved after, and a mount/list/create/write/ fsync/remount/read-back pass shows normal operation unaffected. This was initially reported through [email protected]; per Greg K.H. and Ryusuke Konishi it is being resubmitted here for normal public review. Reproducers (small Python scripts that generate the images) are available on request.
These patches were developed with AI assistance (Anthropic Claude) and manually reviewed and tested.
Quoted 6 lines
Changes in v2 (per Ryusuke Konishi's review of v1):
- Patch 1: also accept S_ISDIR/S_ISLNK (not justS_ISREG), wrap the check inlikely(), return-EINVALinstead of-EIO.
- Patch 2: hoistnilfs_chunk_size(inode)into a localchunk_sizevariable; expanded the comment on why chunk-aligned offsets are already trustworthy without a chain walk.
Hi Jake,
Thank you for sending the v2 patch set. I hope you are recovering well from the flu and that I didn't push you too hard.
Both patches now look good to me, so I will run tests locally and aim to forward them upstream as soon as possible.
Regarding the offset check derived from the pos field of struct dir_context in nilfs_readdir(), I somehow confused records with chunks during the initial review and gave you an incorrect comment. My apologies for that.
As you reinforced in the comment, your first patch proposal was also correct.
Thanks,
Ryusuke Konishi
Quoted 12 lines
Jake Labelle (2):
nilfs2: reject non-regular inodes in dsync recovery
nilfs2: validate directory position after llseek in readdirfs/nilfs2/dir.c | 33 +++++++++++++++++++++++++++++++++ fs/nilfs2/recovery.c | 17 +++++++++++++++++ 2 files changed, 50 insertions(+)--
2.43.0
Ryusuke Konishi
maintainerQuoted 49 lines · Ryusuke Konishi
Quoted 32 lines · Jake Labelle
Hi Ryusuke,
Sorry for the late reply, busy getting the flu 😄. I've put your review comments from v1 into the changes below.
While reviewing fs/nilfs2 I found two robustness issues with corrupted (or malformed) filesystem images, both dating back to the initial merge of nilfs2:
Patch 1: roll-forward recovery replays dsync logs without checking that the designated inode is one of the types that actually have a bmap. A log entry naming some other inode type leads
nilfs_get_block()to an uninitialized bmap and an indirect call through uninitialized memory. With the patch, mount of such an image fails cleanly with-EINVAL.Patch 2:
nilfs_readdir()parses the directory folio at whatever offset llseek left inctx->pos, without snapping it onto an entry boundary the way ext2'sext2_validate_entry()does.dir_emit()can then emit bytes from a bogus entry, reading past the end of the folio.Both patches were tested against current mainline (arm64): each issue reproduces before and is resolved after, and a mount/list/create/write/ fsync/remount/read-back pass shows normal operation unaffected. This was initially reported through [email protected]; per Greg K.H. and Ryusuke Konishi it is being resubmitted here for normal public review. Reproducers (small Python scripts that generate the images) are available on request.
These patches were developed with AI assistance (Anthropic Claude) and manually reviewed and tested.
Quoted 6 lines
Changes in v2 (per Ryusuke Konishi's review of v1):
- Patch 1: also accept S_ISDIR/S_ISLNK (not justS_ISREG), wrap the check inlikely(), return-EINVALinstead of-EIO.
- Patch 2: hoistnilfs_chunk_size(inode)into a localchunk_sizevariable; expanded the comment on why chunk-aligned offsets are already trustworthy without a chain walk.Hi Jake,
Thank you for sending the v2 patch set. I hope you are recovering well from the flu and that I didn't push you too hard.
Both patches now look good to me, so I will run tests locally and aim to forward them upstream as soon as possible.
Quoted 8 lines
Regarding the offset check derived from the pos field of struct
dir_contextinnilfs_readdir(), I somehow confused records with chunks during the initial review and gave you an incorrect comment. My apologies for that.
As you reinforced in the comment, your first patch proposal was also correct.Thanks,
Ryusuke Konishi
Hi Jake,
One small request regarding the patch metadata.
Both patches carry the following tag:
However, since AI tools are not recognized as legal or copyright authors, the "Assisted-by:" tag should be used instead of "Co-Authored-By:". Please refer to Documentation/process/coding-assistants.rst for details.
You don't need to resend the patches for this, but could you let us know the tag string you would like to use formatted for the "Assisted-by:" tag?
Example:
Thanks,
Ryusuke Konishi