From 0129c883459894f3e7101cbfb987f08a2242474b Mon Sep 17 00:00:00 2001
From: Tobias Stoeckmann <tobias@stoeckmann.org>
Date: Sun, 8 Oct 2023 20:41:29 +0200
Subject: [PATCH] lib/path: fix possible out of boundary access

If fgets reads from a file starting with a NUL byte in ul_path_cpuparse,
then the check for newline leads to an out of boundary access.

Proof of Concept (compile with --enable-asan):

1. Prepare /tmp/poc with required files
```
$ install -d /tmp/poc/sys/devices/system/cpu
$ dd if=/dev/zero of=/tmp/poc/sys/devices/system/cpu/possible bs=1 count=1
$ install -D /dev/null /tmp/poc/proc/cpuinfo
```

2. Run lscpu with sysroot option
```
$ lscpu --sysroot /tmp/poc
=================================================================
==78238==ERROR: AddressSanitizer: heap-buffer-overflow
```

Signed-off-by: Tobias Stoeckmann <tobias@stoeckmann.org>
---
 lib/path.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/lib/path.c b/lib/path.c
index bf15ab9..5114e44 100644
--- a/lib/path.c
+++ b/lib/path.c
@@ -1013,7 +1013,7 @@ static int ul_path_cpuparse(struct path_cxt *pc, cpu_set_t **set, int maxcpus, i
 		return rc;
 
 	len = strlen(buf);
-	if (buf[len - 1] == '\n')
+	if (len > 0 && buf[len - 1] == '\n')
 		buf[len - 1] = '\0';
 
 	*set = cpuset_alloc(maxcpus, &setsize, NULL);
-- 
2.33.0

