[PATCH] erofs-utils: lib: add recursion depth limit to erofs_get_pathname_iter

Utkal Singh singhutkal015 at gmail.com
Mon Mar 16 01:28:57 AEDT 2026


erofs_get_pathname_iter() recursively calls erofs_iterate_dir() with
no depth limit.  A crafted EROFS image with deeply nested directories
causes unbounded stack recursion leading to a stack overflow (SIGSEGV).

  erofs_get_pathname()
    erofs_iterate_dir()
      erofs_get_pathname_iter()   <- calls back into iterate_dir
        erofs_iterate_dir()
          erofs_get_pathname_iter()  <- unbounded recursion
            ...

Note that fsck/main.c already protects against directory loops via
fsckcfg.dirstack, but lib/dir.c has no equivalent guard.

Fix by adding a depth counter to erofs_get_pathname_context and
returning -ELOOP when recursion exceeds EROFS_GET_PATHNAME_MAX_DEPTH
(64 levels), consistent with typical filesystem path depth limits.

Signed-off-by: Utkal Singh <singhutkal015 at gmail.com>
---
 lib/dir.c | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/lib/dir.c b/lib/dir.c
index 98edb8e..6a2c838 100644
--- a/lib/dir.c
+++ b/lib/dir.c
@@ -196,12 +196,15 @@ int erofs_iterate_dir(struct erofs_dir_context *ctx, bool fsck)
 
 #define EROFS_PATHNAME_FOUND 1
 
+#define EROFS_GET_PATHNAME_MAX_DEPTH	64
+
 struct erofs_get_pathname_context {
 	struct erofs_dir_context ctx;
 	erofs_nid_t target_nid;
 	char *buf;
 	size_t size;
 	size_t pos;
+	unsigned int depth;
 };
 
 static int erofs_get_pathname_iter(struct erofs_dir_context *ctx)
@@ -249,7 +252,14 @@ static int erofs_get_pathname_iter(struct erofs_dir_context *ctx)
 				.buf = pathctx->buf,
 				.size = pathctx->size,
 				.pos = pos + len + 1,
+				.depth = pathctx->depth + 1,
 			};
+			if (pathctx->depth >= EROFS_GET_PATHNAME_MAX_DEPTH) {
+				erofs_err("pathname lookup depth exceeds %u, nid %llu",
+					  EROFS_GET_PATHNAME_MAX_DEPTH,
+					  dir.nid | 0ULL);
+				return -ELOOP;
+			}
 			ret = erofs_iterate_dir(&nctx.ctx, false);
 			if (ret == EROFS_PATHNAME_FOUND) {
 				pathctx->buf[pos++] = '/';
-- 
2.43.0



More information about the Linux-erofs mailing list