A build step deletes a file, then writes it back a moment later. If anyone else can write to that directory, they can slip a symlink into the gap and redirect your write.
What goes wrong
A code-generation task wants to refresh an output file. It checks whether the file exists, unlinks it, and later writes the new contents to the same path. Reasonable on its own. The problem is the time between the unlink and the write, and who else can touch that directory.
If an attacker has write access to the output directory, they wait for the unlink and drop a symbolic link at the same path, pointing anywhere they choose. Your write follows the link and lands on the target. Now your generated data has overwritten a file the build never intended to touch, maybe a config, a startup script, or something outside the project entirely.
Check-then-use across a filesystem is a race by construction. The path you validated and the path you write are only the same if nothing changed in between, and on a shared directory something can always change in between.
The pattern
target = outDir + '/generated.js'
if exists(target):
unlink(target) # window opens here
data = generate()
writeFile(target, data) # follows a symlink if present
# path checked earlier != path written nowfd = open(target, O_CREAT | O_EXCL | O_WRONLY | O_NOFOLLOW)
# O_EXCL: fail if it exists; O_NOFOLLOW: never follow a symlink
try:
write(fd, generate())
finally:
close(fd)
# or write to a private temp dir, then rename into placeGrounding and reachability were confirmed. The exploit-path gate would not conclude without the calling code, so the finding was held and an evidence request was raised instead of being reported as fact.
Why it matters to you
This lives in build tooling, installers, cache directories, and anything that regenerates files in a shared or world-writable location. On multi-tenant build agents and shared CI, the attacker with write access to that directory is a realistic threat, not a hypothetical. An arbitrary file overwrite there can mean code execution the next time something reads what you clobbered.
Stop separating the check from the write. Open with flags that refuse to follow symlinks and refuse to clobber, or stage output in a directory only you control and rename it into place.
Check your own code
- Grep for exists or stat followed later by open, write, or unlink
- Open output files with no-follow and exclusive-create flags
- Write to a private temp dir and rename into place atomically
- Lock down permissions on any directory your build writes to