locks: fix TOCTOU race when granting write lease
authorAmir Goldstein <amir73il@gmail.com>
Tue, 16 Aug 2022 14:53:17 +0000 (17:53 +0300)
committerAl Viro <viro@zeniv.linux.org.uk>
Tue, 16 Aug 2022 14:59:54 +0000 (10:59 -0400)
commitd6da19c9cace63290ccfccb1fc35151ffefc0bec
tree00e66911e1e16675007d324b91572ab73adac346
parent568035b01cfb107af8d2e4bd2fb9aea22cf5b868
locks: fix TOCTOU race when granting write lease

Thread A trying to acquire a write lease checks the value of i_readcount
and i_writecount in check_conflicting_open() to verify that its own fd
is the only fd referencing the file.

Thread B trying to open the file for read will call break_lease() in
do_dentry_open() before incrementing i_readcount, which leaves a small
window where thread A can acquire the write lease and then thread B
completes the open of the file for read without breaking the write lease
that was acquired by thread A.

Fix this race by incrementing i_readcount before checking for existing
leases, same as the case with i_writecount.

Use a helper put_file_access() to decrement i_readcount or i_writecount
in do_dentry_open() and __fput().

Fixes: 387e3746d01c ("locks: eliminate false positive conflicts for write lease")
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Amir Goldstein <amir73il@gmail.com>
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
fs/file_table.c
fs/internal.h
fs/open.c