Bug 1895831

Summary: passwd command truncates files instead of atomic moves
Product: [Fedora] Fedora Reporter: Коренберг Марк <socketpair>
Component: shadow-utilsAssignee: Iker Pedrosa <ipedrosa>
Status: CLOSED NOTABUG QA Contact: Fedora Extras Quality Assurance <extras-qa>
Severity: medium Docs Contact:
Priority: unspecified    
Version: rawhideCC: ipedrosa, pvrabec, tmraz
Target Milestone: ---   
Target Release: ---   
Hardware: All   
OS: Linux   
Whiteboard:
Fixed In Version: Doc Type: If docs needed, set a value
Doc Text:
Story Points: ---
Clone Of: Environment:
Last Closed: 2020-11-09 08:55:45 UTC Type: Bug
Regression: --- Mount Type: ---
Documentation: --- CRM:
Verified Versions: Category: ---
oVirt Team: --- RHEL 7.3 requirements from Atomic Host:
Cloudforms Team: --- Target Upstream Version:
Embargoed:

Description Коренберг Марк 2020-11-09 08:35:45 UTC
See https://bugzilla.redhat.com/show_bug.cgi?id=1862056


According to strace, it opens /etc/passwd with O_TRUNC and writes new contents. If power outage happened at this point, FS may reveal en empty file. In order to overcome, it MUST:

1. open temporary file in the same dir (i.e. in /etc) securely like mkostemp()
2. copy ownerhsip info, permissions, possibly some attributes (selinux? xattr?) from current file to temporary one
3. fill new file with new data
4. fdatasync(tmpfile)
5. close(tmpfile)
5. rename("/etc/passwd.tmp", "/etc/passwd")
6. dirfd = open("/etc", O_DIRECTORY|O_RDONLY)
7. fdatasync(dirfd)
8. close(dirfd)

This is the only way to secure(safe) replace a file.

If possible, it's better to:
1. Do all the operations using *at syscalls with opened "/etc" at the start of the change operation.
2. use openat(O_TEMPFILE)+ linkat("/proc/self/fd/%d") instead of rename() in order not to leave temporary files on accidental poweroff. If not, remove all temporary files left from the previous call after gaining the main lock.

Comment 1 Tomas Mraz 2020-11-09 08:44:50 UTC
Where do you see that? shadow-utils should not open /etc/passwd with O_TRUNC at all. Could you attach the strace where this would be visible?

Comment 2 Коренберг Марк 2020-11-09 08:55:45 UTC
Sorry, my fault. It does not open /etc/passwd with O_TRUNC.