Skip to content

harden output file handling against race conditions and symlink attacks - #4640

Closed
metsw24-max wants to merge 2 commits into
meta:devfrom
metsw24-max:cli-output-file-hardening
Closed

metsw24-max wants to merge 2 commits into
meta:devfrom
metsw24-max:cli-output-file-hardening

Conversation

@metsw24-max

Copy link
Copy Markdown

This change hardens the CLI output file creation path by eliminating race-prone patterns and preventing symlink-based overwrite attacks.

The update replaces the existing unlink-and-recreate workflow with atomic file creation semantics and introduces additional safety checks for output file handling

Replace non-atomic unlink() + open() pattern with atomic open using O_EXCL for non-overwrite mode

Prevent symlink traversal during output file creation using O_NOFOLLOW

Add O_CLOEXEC to reduce file descriptor leakage across exec boundaries

Introduce explicit handling of EEXIST and ELOOP for clearer and safer error reporting

@meta-cla meta-cla Bot added the CLA Signed label Apr 8, 2026
Fold the open flag construction into the declaration initialiser so it
stays C89-compliant (-Wdeclaration-after-statement was tripping -Werror
on the FreeBSD job). Also mark the new cli-test executable so the runner
can launch it.
@metsw24-max

Copy link
Copy Markdown
Author

Pushed a fix for the FreeBSD job. The open flags were being built with a couple of statements between the two declarations, which trips -Wdeclaration-after-statement under -Werror on that build. Folded them back into the initialiser so it stays C89-clean, and marked the new cli-test executable so the runner picks it up.

@metsw24-max

Copy link
Copy Markdown
Author

any update?

@Cyan4973

Cyan4973 commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Thank you for this PR, and sorry for the long wait.

You are right that the output could be written through a symbolic link: a dangling link at the output path was followed, even without -f. It's fixed in #4906, with a different approach, because unfortunately this one breaks some legitimate outputs:

  • O_NOFOLLOW rejects -o /dev/stdout and -o /dev/fd/N (process substitution), which are symbolic links.
  • O_EXCL without -f rejects existing outputs that are not regular files, such as -o /dev/null and named pipes.
  • Truncating an existing file in place, instead of removing it first, writes through hard links.

#4906 creates new files with O_EXCL, as gzip and xz do, treats a dangling link as an existing file, and still opens existing devices and pipes. I'm closing this PR as superseded by #4906.

Regards

@Cyan4973 Cyan4973 closed this Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants