vfs: fix TOCTOU race condition

Signed-off-by: Michael Shaw <m@michaelsshaw.com>
This commit is contained in:
Michael Shaw 2026-07-05 14:47:00 +02:00
commit 36d90bc0f6
2 changed files with 23 additions and 13 deletions

View file

@ -11,10 +11,9 @@ static mem_cache_t *dirent_slab = NULL;
int inode_populate_dirents(inode_t *inode) int inode_populate_dirents(inode_t *inode)
{ {
write_lock(&inode->rwlock); /* write_lock(&inode-rwlock) is held by caller */
if (inode->dirents.head != NULL) { if (inode->dirents.head != NULL) {
write_unlock(&inode->rwlock);
return -EINVAL; return -EINVAL;
} }
@ -38,8 +37,6 @@ int inode_populate_dirents(inode_t *inode)
kfree(dents); kfree(dents);
write_unlock(&inode->rwlock);
return 0; return 0;
} }
@ -48,12 +45,16 @@ int inode_find_dirent(inode_t *inode, const char *name, dirent_t **out)
if (inode->mode != INODE_DIRECTORY) if (inode->mode != INODE_DIRECTORY)
return -ENOTDIR; return -ENOTDIR;
ssize_t res;
if (inode->dirents.head == NULL) { if (inode->dirents.head == NULL) {
res = inode_populate_dirents(inode); write_lock(&inode->rwlock);
if (inode->dirents.head == NULL) {
ssize_t res = inode_populate_dirents(inode);
write_unlock(&inode->rwlock);
if (res < 0) if (res < 0)
return res; return res;
} else {
write_unlock(&inode->rwlock);
}
} }
list_item_t *item = inode->dirents.head; list_item_t *item = inode->dirents.head;

View file

@ -187,6 +187,17 @@ int vfs_creat(dirent_t *parent, const char *name, u64 mode, int flags, dirent_t
dirent_t *test = NULL; dirent_t *test = NULL;
res = inode_find_dirent(ino, name, &test); 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) { if (res == 0) {
/* exists */ /* exists */
ret = -EEXIST; ret = -EEXIST;
@ -197,8 +208,6 @@ int vfs_creat(dirent_t *parent, const char *name, u64 mode, int flags, dirent_t
goto out_err; goto out_err;
} }
write_lock(&ino->rwlock);
/* create inode */ /* create inode */
fs_t *fs = parent->fs; fs_t *fs = parent->fs;
inode_t *new_ino; inode_t *new_ino;