vfs: fix TOCTOU race condition
Signed-off-by: Michael Shaw <m@michaelsshaw.com>
This commit is contained in:
parent
7556c3170e
commit
36d90bc0f6
2 changed files with 23 additions and 13 deletions
|
|
@ -11,12 +11,11 @@ static mem_cache_t *dirent_slab = NULL;
|
|||
|
||||
int inode_populate_dirents(inode_t *inode)
|
||||
{
|
||||
write_lock(&inode->rwlock);
|
||||
/* write_lock(&inode-rwlock) is held by caller */
|
||||
|
||||
if (inode->dirents.head != NULL) {
|
||||
write_unlock(&inode->rwlock);
|
||||
return -EINVAL;
|
||||
}
|
||||
}
|
||||
|
||||
dirent_t *dents;
|
||||
ssize_t n = inode->i_ops.get_dents(inode, &dents);
|
||||
|
|
@ -38,8 +37,6 @@ int inode_populate_dirents(inode_t *inode)
|
|||
|
||||
kfree(dents);
|
||||
|
||||
write_unlock(&inode->rwlock);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
|
@ -48,12 +45,16 @@ int inode_find_dirent(inode_t *inode, const char *name, dirent_t **out)
|
|||
if (inode->mode != INODE_DIRECTORY)
|
||||
return -ENOTDIR;
|
||||
|
||||
ssize_t res;
|
||||
|
||||
if (inode->dirents.head == NULL) {
|
||||
res = inode_populate_dirents(inode);
|
||||
if (res < 0)
|
||||
return res;
|
||||
write_lock(&inode->rwlock);
|
||||
if (inode->dirents.head == NULL) {
|
||||
ssize_t res = inode_populate_dirents(inode);
|
||||
write_unlock(&inode->rwlock);
|
||||
if (res < 0)
|
||||
return res;
|
||||
} else {
|
||||
write_unlock(&inode->rwlock);
|
||||
}
|
||||
}
|
||||
|
||||
list_item_t *item = inode->dirents.head;
|
||||
|
|
@ -98,7 +99,7 @@ void inode_free(inode_t *inode)
|
|||
item = item->next;
|
||||
}
|
||||
}
|
||||
list_destroy(&inode->dirents);
|
||||
list_destroy(&inode->dirents);
|
||||
slab_free(inode_slab, inode);
|
||||
}
|
||||
|
||||
|
|
|
|||
13
fs/vfs/vfs.c
13
fs/vfs/vfs.c
|
|
@ -187,6 +187,17 @@ int vfs_creat(dirent_t *parent, const char *name, u64 mode, int flags, dirent_t
|
|||
dirent_t *test = NULL;
|
||||
res = inode_find_dirent(ino, name, &test);
|
||||
|
||||
/* best-effort first check */
|
||||
if (res == 0) {
|
||||
dirent_dec_ref_lock(test);
|
||||
return -EEXIST;
|
||||
}
|
||||
|
||||
write_lock(&ino->rwlock);
|
||||
|
||||
/* re-check under lock */
|
||||
test = NULL;
|
||||
res = inode_find_dirent(ino, name, &test);
|
||||
if (res == 0) {
|
||||
/* exists */
|
||||
ret = -EEXIST;
|
||||
|
|
@ -197,8 +208,6 @@ int vfs_creat(dirent_t *parent, const char *name, u64 mode, int flags, dirent_t
|
|||
goto out_err;
|
||||
}
|
||||
|
||||
write_lock(&ino->rwlock);
|
||||
|
||||
/* create inode */
|
||||
fs_t *fs = parent->fs;
|
||||
inode_t *new_ino;
|
||||
|
|
|
|||
Loading…
Reference in a new issue