Repository navigation
fix: restore home ownership for exported users - #1326
Conversation
There was a problem hiding this comment.
Hey - I've found 7 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="accounts1/manager.go" line_range="418" />
<code_context>
+ if stat.Uid == uint32(uid) && stat.Gid == uint32(gid) {
+ return nil
+ }
+ return recoverOwnership(u)
+}
+
</code_context>
<issue_to_address>
**Symlink race chowns files outside home**
When an exported user has a writable subdirectory in a home with matching UID but mismatched GID and starts a session, `checkHomeOwnership` calls `recoverOwnership`; racing `filepath.Walk` to replace a traversed directory with a symlink makes `os.Lchown` reach an outside file through that intermediate symlink and give it to the user.
Walk via directory file descriptors with no-follow operations and reject paths that escape the opened home.
</issue_to_address>
### Comment 2
<location path="accounts1/manager.go" line_range="418" />
<code_context>
+ if stat.Uid == uint32(uid) && stat.Gid == uint32(gid) {
+ return nil
+ }
+ return recoverOwnership(u)
+}
+
</code_context>
<issue_to_address>
**Symlink targets retain wrong ownership**
When the home path is a symlink and its target has mismatched ownership, `syscall.Stat` detects the target’s ownership, but `recoverOwnership` uses `filepath.Walk` and `os.Lchown` without following the home symlink, so it changes only the link and reports success while the target remains misowned.
Make ownership recovery safely walk and chown the symlink target rather than only the link.
Also at `accounts1/manager.go:415`.
</issue_to_address>
### Comment 3
<location path="accounts1/manager.go" line_range="404-412" />
<code_context>
+ return errors.New("missing user for home ownership check")
+ }
+ var stat syscall.Stat_t
+ if err := syscall.Stat(u.HomeDir, &stat); err != nil {
+ return err
+ }
+ uid, err := strconv.ParseUint(u.Uid, 10, 32)
+ if err != nil {
+ return err
+ }
</code_context>
<issue_to_address>
**Recovery uses inconsistent user properties**
When a passwd update changes a user’s home directory or GID while ownership recovery is running, `checkHomeOwnership` reads properties without `PropsMu`, and `recoverOwnership` reads them again, so the update can make recovery use a mixed or stale home directory and GID, leaving ownership incorrect or applying the wrong group.
Read the user properties under `PropsMu` and ensure recovery uses that same consistent snapshot.
Also at `accounts1/manager.go:430`.
</issue_to_address>
### Comment 4
<location path="accounts1/manager.go" line_range="486" />
<code_context>
- if err != nil {
- logger.Warning(err)
- }
+ if err := checkHomeOwnership(u); err != nil {
+ return err
}
</code_context>
<issue_to_address>
**Startup exports homes without recovery**
When the daemon starts with previously logged-in users already loaded into `usersMap`, including after a reset, `Daemon.Start` calls `exportUsers`, which exports cached users through `service.Export` without calling `checkHomeOwnership`; their preserved homes therefore remain incorrectly owned when the users are exposed.
Call `checkHomeOwnership` for cached users on the `exportUsers` startup path before exporting them.
Also at `accounts1/manager.go:430`.
</issue_to_address>
### Comment 5
<location path="accounts1/manager.go" line_range="415" />
<code_context>
+ if err != nil {
+ return err
+ }
+ if stat.Uid == uint32(uid) && stat.Gid == uint32(gid) {
+ return nil
+ }
</code_context>
<issue_to_address>
**Retries skip misowned descendants**
When recovery fixes the home root but fails on a descendant, then the caller retries, `checkHomeOwnership` sees that the root UID and GID now match and returns without walking the home again, leaving descendants incorrectly owned while the retry reports success.
Ensure retries verify and recover ownership throughout the home tree, not only at its root.
</issue_to_address>
### Comment 6
<location path="accounts1/manager.go" line_range="487" />
<code_context>
+ }
+ var stat syscall.Stat_t
+ if err := syscall.Stat(u.HomeDir, &stat); err != nil {
+ return err
+ }
+ uid, err := strconv.ParseUint(u.Uid, 10, 32)
</code_context>
<issue_to_address>
**User creation reports a timeout**
When `CreateUser` has registered its channel and the ownership check fails during export, `exportUserByUid` returns before notifying `userAddedChanMap`, and `addUser` only logs the error, so `CreateUser` remains blocked until its 60-second timeout instead of receiving the ownership failure.
Notify the registered creation channel of the ownership error before returning from the export path.
</issue_to_address>
### Comment 7
<location path="accounts1/manager.go" line_range="486" />
<code_context>
- if err != nil {
- logger.Warning(err)
- }
+ if err := checkHomeOwnership(u); err != nil {
+ return err
}
</code_context>
<issue_to_address>
**Transient home errors block export**
When a newly added user's home is temporarily unavailable or ownership recovery temporarily fails during the passwd-change event, `checkHomeOwnership` returns a transient `stat` or recursive recovery error before export, and `addUser` only logs the error and returns. The user stays unexported until another passwd-change event happens; no retry is scheduled for that failure.
Retry failed user exports after transient home-access or ownership-recovery errors.
</issue_to_address>2ab79c7 to
84cf7d0
Compare
|
/test all |
|
@sourcery-ai review |
Reviewer's GuideImplementationAdd descriptor-pinned home ownership recovery with account-path validation, mount-boundary and hard-link safeguards, and optional failure handling.
Integrate home preparation into publication for existing and new users, and return errors from user construction before attempting export.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
84cf7d0 to
661626b
Compare
There was a problem hiding this comment.
Hey - I've found 9 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="accounts1/manager.go" line_range="407" />
<code_context>
m.usersMapMu.Unlock()
if alreadyExported {
- return nil
+ return m.exportPreparedUser(exportedUser, userPath)
}
</code_context>
<issue_to_address>
**Deleted accounts get republished**
When a user is deleted while recovery for an already-exported user is in progress, `exportPreparedUser` sees the removed user as a fresh export and calls `service.Export`, adding the deleted account back to D-Bus and `usersMap`.
Prevent recovery from exporting a user after deletion has removed it from the manager.
</issue_to_address>
### Comment 2
<location path="accounts1/ownership_linux.go" line_range="147-150" />
<code_context>
+ if st.Uid == uint32(r.uid) && st.Gid == uint32(r.gid) {
+ return nil
+ }
+ if st.Mode&unix.S_IFMT == unix.S_IFREG && st.Nlink > 1 {
+ return errors.New("refusing to change ownership of a multiply-linked regular file")
+ }
+ return r.chown(fd, r.uid, r.gid)
+}
+
</code_context>
<issue_to_address>
**Hardlink race changes outside files**
When a process able to link a regular file in the home adds another hard link between the link-count check and `r.chown`, `visit` checks `st.Nlink` and then calls `r.chown` in separate operations, so a concurrent process can add a hard link after the check and have the ownership change affect the file through that outside link.
Prevent concurrent hard-link creation for the duration of the check and ownership change, or conservatively avoid chowning regular files whose link count can change during recovery.
</issue_to_address>
### Comment 3
<location path="accounts1/ownership_linux.go" line_range="172" />
<code_context>
+ if err != nil {
+ return fmt.Errorf("open recovery entry %q: %w", name, err)
+ }
+ err = r.visit(child, depth+1)
+ unix.Close(child)
+ if err != nil {
</code_context>
<issue_to_address>
**Moved files are chowned outside home**
When a process with write access to a traversed directory renames an opened entry out of the home while recovery is processing it, `visit` continues using the pinned child descriptor after the entry is renamed out of the home tree, and `r.chown` changes that inode’s ownership anyway. A concurrent home-directory writer can therefore cause recovery to alter ownership of an object that is no longer in the account’s home.
Before changing ownership, verify that the pinned entry is still reachable under the recovery root, or otherwise prevent concurrent namespace changes during recovery.
</issue_to_address>
### Comment 4
<location path="accounts1/manager.go" line_range="463" />
<code_context>
- if err != nil {
- logger.Warning(err)
- }
+ return m.exportPreparedUser(u, userPath)
+}
+
</code_context>
<issue_to_address>
**Startup users miss home recovery**
When a user is loaded into `usersMap` before daemon startup exports it, `exportUsers` calls `service.Export` directly instead of `exportPreparedUser`, so the user's preserved home retains stale ownership when the account is first exported.
Route startup exports through `exportPreparedUser` so recovery runs before each user is exported.
Also at `accounts1/manager.go:407`.
</issue_to_address>
### Comment 5
<location path="accounts1/ownership_linux.go" line_range="220-221" />
<code_context>
+ if err := unix.Fstat(int(home.Fd()), &st); err != nil {
+ return err
+ }
+ if !force && st.Uid == uint32(uid) && st.Gid == uint32(gid) {
+ return nil
+ }
+ return recoverOwnershipAt(home, uid, gid)
</code_context>
<issue_to_address>
**Descendant ownership stays stale**
When the home directory already has the target UID and GID but one or more descendants do not, `prepareRecoveryHome` returns before calling `recoverOwnershipAt`, so descendants keep their stale ownership while recovery reports success and the user can still lack access to them.
Traverse the home even when its top-level UID and GID already match the target.
</issue_to_address>
### Comment 6
<location path="accounts1/ownership_linux.go" line_range="138" />
<code_context>
+ exportedUser, alreadyExported := m.usersMap[userPath]
m.usersMapMu.Unlock()
if alreadyExported {
- return nil
+ return m.exportPreparedUser(exportedUser, userPath)
}
</code_context>
<issue_to_address>
**Special entries retain stale owners**
When a home contains a FIFO, socket, device node, or other special file whose ownership differs from the account, `ownershipRecovery.visit` returns without changing ownership for these entries, so they retain their old UID and GID after recovery and owner-dependent access can fail.
Have `visit` change ownership of special entries before returning.
</issue_to_address>
### Comment 7
<location path="accounts1/manager.go" line_range="471" />
<code_context>
+ return errors.New("missing user for export")
+ }
+ u.PropsMu.RLock()
+ snapshot := homeOwnershipSnapshot{userName: u.UserName, uid: u.Uid, gid: u.Gid, path: u.HomeDir}
+ u.PropsMu.RUnlock()
+
</code_context>
<issue_to_address>
**Recovery uses stale account properties**
When the passwd-change handler updates a user's GID or home path after the recovery snapshot is taken but before recovery finishes, `exportPreparedUser` continues with the old snapshot while `handleFilePasswdChanged` updates the account, so recovery changes ownership for the old properties and the exported account can have a mismatched home.
Serialize property updates with recovery or revalidate the snapshot before exporting the user.
</issue_to_address>
### Comment 8
<location path="accounts1/ownership_linux.go" line_range="175-176" />
<code_context>
+ err = r.visit(child, depth+1)
+ unix.Close(child)
+ if err != nil {
+ return fmt.Errorf("recover entry %q: %w", name, err)
+ }
+ }
+ if readErr == io.EOF {
</code_context>
<issue_to_address>
**One unsafe entry blocks recovery**
When a home contains a multiply linked regular file with mismatched ownership or a nested mount, `visitChildren` returns on the first child error, so `visit` never reaches the home-directory chown. A multiply linked file or nested mount can therefore leave the top-level home owned by the old UID/GID, preventing the user from entering it even though account export succeeds.
Record and log unsafe entries while continuing over other children, then still attempt to chown the home directory last.
</issue_to_address>
### Comment 9
<location path="accounts1/manager.go" line_range="474" />
<code_context>
+ snapshot := homeOwnershipSnapshot{userName: u.UserName, uid: u.Uid, gid: u.Gid, path: u.HomeDir}
+ u.PropsMu.RUnlock()
+
+ if err := prepareRecoveryHome(snapshot, false); err != nil && !errors.Is(err, os.ErrNotExist) {
+ logger.Warningf("optional home recovery failed for %s: %v", snapshot.userName, err)
}
</code_context>
<issue_to_address>
**Missing homes go unreported**
When the home path is absent because a preserved-home mount or directory is temporarily unavailable, `exportPreparedUser` suppresses `os.ErrNotExist`, so an unavailable preserved home—such as one hidden because its mount is missing—skips recovery without a warning and the account is still exported with no diagnostic for operators.
Log missing-home recovery skips distinctly, or distinguish an expected absent home from an unavailable preserved-home mount.
</issue_to_address>| if st.Mode&unix.S_IFMT == unix.S_IFREG && st.Nlink > 1 { | ||
| return errors.New("refusing to change ownership of a multiply-linked regular file") | ||
| } | ||
| return r.chown(fd, r.uid, r.gid) |
There was a problem hiding this comment.
🟠 High · Hardlink race changes outside files
When a process able to link a regular file in the home adds another hard link between the link-count check and r.chown, visit checks st.Nlink and then calls r.chown in separate operations, so a concurrent process can add a hard link after the check and have the ownership change affect the file through that outside link.
Prevent concurrent hard-link creation for the duration of the check and ownership change, or conservatively avoid chowning regular files whose link count can change during recovery.
Prompt for AI agents
In `accounts1/ownership_linux.go` at lines 147-150:
**Hardlink race changes outside files**
When a process able to link a regular file in the home adds another hard link between the link-count check and `r.chown`, `visit` checks `st.Nlink` and then calls `r.chown` in separate operations, so a concurrent process can add a hard link after the check and have the ownership change affect the file through that outside link.
Prevent concurrent hard-link creation for the duration of the check and ownership change, or conservatively avoid chowning regular files whose link count can change during recovery.There was a problem hiding this comment.
Agreed. The link count check and ownership change are separate operations. The current guard rejects regular files already observed to have multiple links. Handling concurrent changes requires separate coordination.
| return errors.New("missing user for export") | ||
| } | ||
| u.PropsMu.RLock() | ||
| snapshot := homeOwnershipSnapshot{userName: u.UserName, uid: u.Uid, gid: u.Gid, path: u.HomeDir} |
There was a problem hiding this comment.
🟡 Medium · Recovery uses stale account properties
When the passwd-change handler updates a user's GID or home path after the recovery snapshot is taken but before recovery finishes, exportPreparedUser continues with the old snapshot while handleFilePasswdChanged updates the account, so recovery changes ownership for the old properties and the exported account can have a mismatched home.
Serialize property updates with recovery or revalidate the snapshot before exporting the user.
Prompt for AI agents
In `accounts1/manager.go` at line 471:
**Recovery uses stale account properties**
When the passwd-change handler updates a user's GID or home path after the recovery snapshot is taken but before recovery finishes, `exportPreparedUser` continues with the old snapshot while `handleFilePasswdChanged` updates the account, so recovery changes ownership for the old properties and the exported account can have a mismatched home.
Serialize property updates with recovery or revalidate the snapshot before exporting the user.There was a problem hiding this comment.
Agreed. The snapshot keeps inputs consistent within one recovery but can become stale afterward. Rechecking before export would not undo any ownership changes.
| return fmt.Errorf("recover entry %q: %w", name, err) | ||
| } |
There was a problem hiding this comment.
🟡 Medium · One unsafe entry blocks recovery
When a home contains a multiply linked regular file with mismatched ownership or a nested mount, visitChildren returns on the first child error, so visit never reaches the home-directory chown. A multiply linked file or nested mount can therefore leave the top-level home owned by the old UID/GID, preventing the user from entering it even though account export succeeds.
Record and log unsafe entries while continuing over other children, then still attempt to chown the home directory last.
Prompt for AI agents
In `accounts1/ownership_linux.go` at lines 175-176:
**One unsafe entry blocks recovery**
When a home contains a multiply linked regular file with mismatched ownership or a nested mount, `visitChildren` returns on the first child error, so `visit` never reaches the home-directory chown. A multiply linked file or nested mount can therefore leave the top-level home owned by the old UID/GID, preventing the user from entering it even though account export succeeds.
Record and log unsafe entries while continuing over other children, then still attempt to chown the home directory last.There was a problem hiding this comment.
Confirmed. Nested mounts and multiply linked regular files that need an ownership change stop recovery before the home root is updated. This preserves the retry trigger. The lql tests passed in both orders, but did not exercise this condition.
| snapshot := homeOwnershipSnapshot{userName: u.UserName, uid: u.Uid, gid: u.Gid, path: u.HomeDir} | ||
| u.PropsMu.RUnlock() | ||
|
|
||
| if err := prepareRecoveryHome(snapshot, false); err != nil && !errors.Is(err, os.ErrNotExist) { |
There was a problem hiding this comment.
🟡 Medium · Missing homes go unreported
When the home path is absent because a preserved-home mount or directory is temporarily unavailable, exportPreparedUser suppresses os.ErrNotExist, so an unavailable preserved home—such as one hidden because its mount is missing—skips recovery without a warning and the account is still exported with no diagnostic for operators.
Log missing-home recovery skips distinctly, or distinguish an expected absent home from an unavailable preserved-home mount.
Prompt for AI agents
In `accounts1/manager.go` at line 474:
**Missing homes go unreported**
When the home path is absent because a preserved-home mount or directory is temporarily unavailable, `exportPreparedUser` suppresses `os.ErrNotExist`, so an unavailable preserved home—such as one hidden because its mount is missing—skips recovery without a warning and the account is still exported with no diagnostic for operators.
Log missing-home recovery skips distinctly, or distinguish an expected absent home from an unavailable preserved-home mount.There was a problem hiding this comment.
Confirmed. ENOENT is suppressed because an absent home can be expected for a new account. Debug logging could distinguish a missing path from recovery that was never triggered.
1. Prepare preserved homes for existing and newly exported users. 2. Snapshot account properties and restore UID and GID without following directory symlinks, updating the home directory last. 3. Pin entries by file descriptor to avoid path replacement races. Refuse to cross mount boundaries or chown multiply linked regular files. 4. Log optional recovery failures and allow account export to proceed. 5. Keep existing-user recovery separate from export so concurrent deletion cannot republish the old object. Log: Restore AD user home ownership after a factory reset Influence: 1. Verify first AD login after joining the domain before restarting the daemon. 2. Repeat with the daemon restarted before joining the domain. 3. Verify a home recovery error does not block account export. fix: 修复已导出用户的家目录属主恢复 1. 对已导出和新导出的用户检查保留家目录。 2. 使用账户属性快照恢复 UID 和 GID,不跟随目录符号链接, 最后修改家目录顶层属主。 3. 通过文件描述符固定遍历对象,防止路径替换竞争。 拒绝跨挂载点恢复及修改具有多个硬链接的普通文件的属主。 4. 可选恢复失败时记录告警,继续账户导出。 5. 已有用户恢复后直接返回,避免并发删除后重新导出旧对象。 Influence: 1. 验证恢复出厂后先加域再重启服务,首次登录时属主正确恢复。 2. 验证先重启服务再加域,首次登录时属主正确恢复。 3. 验证家目录恢复失败时账户仍可导出。 Log: 修复恢复出厂后 AD 域用户家目录属主恢复遗漏 PMS: BUG-383203
661626b to
9ba6920
Compare
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: 52cyb, fly602 The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
|
/forcemerge |
|
This pr force merged! (status: unstable) |
888511a
into
linuxdeepin:release/2500u2-pajil
directory symlinks, updating the home directory last.
Refuse to cross mount boundaries or chown multiply linked regular files.
Log: Restore AD user home ownership after a factory reset
Influence:
fix: 修复已导出用户的家目录属主恢复
最后修改家目录顶层属主。
拒绝跨挂载点恢复及修改具有多个硬链接的普通文件的属主。
Influence:
Log: 修复恢复出厂后 AD 域用户家目录属主恢复遗漏
PMS: BUG-383203
Summary by Sourcery
Restore exported users’ home-directory ownership safely during account publication and recovery.
Bug Fixes:
Enhancements: