Skip to contentSkip to conversation

openat, mkdirat, and TOCTOU for directory creation

DISCUSSION Drew DeVault 2 participants 3 messages Feb 27, 2021 VFS

lore
Share & tools
lore
#0 lore raw

Hiya! I'm looking into the mkdirat and openat syscalls, and I noticed that there's no means of implementing TOCTOU (time-of-check to time-of-use, a technique for preventing race conditions) on directory creation.

To create a directory and obtain a dirfd for it, you have to (1) mkdirat, then (2) openat with O_DIRECTORY, and if the directory is removed in between, the latter will fail.

One possibly straightforward solution is to support openat with the O_DIRECTORY and O_CREAT flags specified.

The present behavior of this flag combination is to create a file and return ENOTDIR. The appropriate behavior is probably to create a directory as proposed, or, at a minimum, to return EINVAL and not create the file.

#1 lore raw
Quoted 11 lines · Drew DeVault

Hiya! I'm looking into the mkdirat and openat syscalls, and I noticed that there's no means of implementing TOCTOU (time-of-check to time-of-use, a technique for preventing race conditions) on directory creation.

To create a directory and obtain a dirfd for it, you have to (1) mkdirat, then (2) openat with O_DIRECTORY, and if the directory is removed in between, the latter will fail.

One possibly straightforward solution is to support openat with the O_DIRECTORY and O_CREAT flags specified.

This was discussed last year[1]. I think it would be useful but it shouldn't be done as part of openat(2) because we already have enough multiplexing with that syscall.

Maybe a mkdirat2(2) (which takes a flags argument -- sigh) that can be told to return a handle to the new directory would be a nicer API.

Quoted 4 lines

The present behavior of this flag combination is to create a file and return ENOTDIR. The appropriate behavior is probably to create a directory as proposed, or, at a minimum, to return EINVAL and not create the file.

Changing the semantics of open scares me a fair bit -- you could probably change openat2(2) since it's not as widely used yet.

[1]: https://lore.kernel.org/linux-fsdevel/20200316142057.xo24zea3k5zwswra@yavin/

Signature · 4 lines
Aleksa Sarai
Senior Software Engineer (Containers)
SUSE Linux GmbH
<https://www.cyphar.com/>
#2 lore raw
Quoted 2 lines · Aleksa Sarai

Maybe a mkdirat2(2) (which takes a flags argument -- sigh) that can be told to return a handle to the new directory would be a nicer API.

That seems appropriate. Hear hear on the sigh.

Quoted 2 lines

Changing the semantics of open scares me a fair bit -- you could probably change openat2(2) since it's not as widely used yet.

Seems agreeable, at least for a start.