In the Linux kernel, the following vulnerability has been resolved:
tracing: Have format file honor EVENTFILEFL_FREED
When eventfs was introduced, special care had to be done to coordinate the freeing of the file meta data with the files that are exposed to user space. The file meta data would have a ref count that is set when the file is created and would be decremented and freed after the last user that opened the file closed it. When the file meta data was to be freed, it would set a flag (EVENTFILEFLFREED) to denote that the file is freed, and any new references made (like new opens or reads) would fail as it is marked freed. This allowed other meta data to be freed after this flag was set (under the eventmutex).
All the files that were dynamically created in the events directory had a pointer to the file meta data and would call event_release() when the last reference to the user space file was closed. This would be the time that it is safe to free the file meta data.
A shortcut was made for the "format" file. It's i_private would point to the "call" entry directly and not point to the file's meta data. This is because all format files are the same for the same "call", so it was thought there was no reason to differentiate them. The other files maintain state (like the "enable", "trigger", etc). But this meant if the file were to disappear, the "format" file would be unaware of it.
This caused a race that could be trigger via the userevents test (that would create dynamic events and free them), and running a loop that would read the userevents format files:
In one console run:
# cd tools/testing/selftests/userevents # while true; do ./ftracetest; done
And in another console run:
# cd /sys/kernel/tracing/ # while true; do cat events/userevents/testevent/format; done 2>/dev/null
With KASAN memory checking, it would trigger a use-after-free bug report (which was a real bug). This was because the format file was not checking the file's meta data flag "EVENTFILEFL_FREED", so it would access the event that the file meta data pointed to after the event was freed.
After inspection, there are other locations that were found to not check the EVENTFILEFLFREED flag when accessing the traceeventfile. Add a new helper function: eventfilefile() that will make sure that the eventmutex is held, and will return NULL if the traceeventfile has the EVENTFILEFLFREED flag set. Have the first reference of the struct file pointer use eventfilefile() and check for NULL. Later uses can still use the eventfiledata() helper function if the eventmutex is still held and was not released since the eventfilefile() call.