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;