From 6633fb0779fb0e6f2968d81e669d0be3578f993c Mon Sep 17 00:00:00 2001 From: Jaroslav Kysela Date: Mon, 30 Nov 2026 14:53:15 +0100 Subject: [PATCH] ucm: fix TOCTOU race in sysfs value substitution Separately checking a file's state (lstat64) before opening it lets the final path component be replaced in between, so the subsequent open() may operate on a different object than was checked. Probe and operate on the same object instead: read the link first and, if the path is not a symlink, open it with O_NOFOLLOW and run the type and permission checks on the opened descriptor via fstat64(). O_NOFOLLOW only constrains the final component, so the symbolic links that sysfs uses for the intermediate components are still resolved as before. Also tighten the accepted value source to regular files only. Based on a patch by Mingjie Shen. Closes: https://github.com/alsa-project/alsa-lib/pull/367 Signed-off-by: Jaroslav Kysela --- src/ucm/ucm_subs.c | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/src/ucm/ucm_subs.c b/src/ucm/ucm_subs.c index e4a238a9..96a1a448 100644 --- a/src/ucm/ucm_subs.c +++ b/src/ucm/ucm_subs.c @@ -744,28 +744,32 @@ static char *rval_sysfs_main(snd_use_case_mgr_t *uc_mgr, const char *top_path, c snprintf(path, sizeof(path), "%s/%s/%s", e, top_path, id); else snprintf(path, sizeof(path), "%s/%s", e, id); - if (lstat64(path, &sb) != 0) - return NULL; - if (S_ISLNK(sb.st_mode)) { - len = readlink(path, link, sizeof(link) - 1); - if (len <= 0) { - snd_error(UCM, "sysfs: cannot read link '%s' (%d)", path, errno); - return NULL; - } + /* Avoid a TOCTOU race: do not stat the path first and open it afterwards */ + len = readlink(path, link, sizeof(link) - 1); + if (len >= 0) { link[len] = '\0'; e = strrchr(link, '/'); if (e) return strdup(e + 1); return NULL; } - if (S_ISDIR(sb.st_mode)) - return NULL; - if ((sb.st_mode & S_IRUSR) == 0) + if (errno != EINVAL) + /* EINVAL means "not a symlink" - proceed to open the file */ return NULL; - fd = open(path, O_RDONLY); + /* Use O_NOFOLLOW to close the race window */ + fd = open(path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC); if (fd < 0) { - snd_error(UCM, "sysfs open failed for '%s' (%d)", path, errno); + if (errno != ENOENT && errno != ELOOP) + snd_error(UCM, "sysfs open failed for '%s' (%d)", path, errno); + return NULL; + } + if (fstat64(fd, &sb) != 0) { + close(fd); + return NULL; + } + if (!S_ISREG(sb.st_mode) || (sb.st_mode & S_IRUSR) == 0) { + close(fd); return NULL; } len = sizeof(path) - 1; -- 2.52.0