Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 29 additions & 14 deletions accounts1/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -399,12 +399,12 @@ func (m *Manager) exportUserByUid(uId string) error {
userPath := userDBusPathPrefix + uId
id, _ := strconv.Atoi(uId)

// 快速路径:已导出则直接返回
// 已导出的用户仍需检查家目录,避免跳过属主修复。
m.usersMapMu.Lock()
_, alreadyExported := m.usersMap[userPath]
exportedUser, alreadyExported := m.usersMap[userPath]
m.usersMapMu.Unlock()
if alreadyExported {
return nil
return prepareUserHome(exportedUser)
}

var err error
Expand Down Expand Up @@ -437,6 +437,9 @@ func (m *Manager) exportUserByUid(uId string) error {
}

u, err = NewDomainUser(uint32(id), m.service, userGroups)
if err != nil {
return err
}

if users.IsLDAPDomainUserID(uId) {
var config = &domainUserConfig{
Expand All @@ -457,30 +460,42 @@ func (m *Manager) exportUserByUid(uId string) error {
return err
}

var stat = &syscall.Stat_t{}
if err := syscall.Stat(u.HomeDir, stat); err != nil {
logger.Warning(err)
} else if strconv.Itoa(int(stat.Uid)) != u.Uid {
logger.Debug("incorrect ownership")
err = recoverOwnership(u)
if err != nil {
logger.Warning(err)
}
return m.exportPreparedUser(u, userPath)
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
}

func prepareUserHome(u *User) error {
if u == nil {
return errors.New("missing user for export")
}
u.PropsMu.RLock()
snapshot := homeOwnershipSnapshot{userName: u.UserName, uid: u.Uid, gid: u.Gid, path: u.HomeDir}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. The snapshot keeps inputs consistent within one recovery but can become stale afterward. Rechecking before export would not undo any ownership changes.

u.PropsMu.RUnlock()

if err := prepareRecoveryHome(snapshot, false); err != nil && !errors.Is(err, os.ErrNotExist) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

logger.Warningf("optional home recovery failed for %s: %v", snapshot.userName, err)
}

return nil
}

func (m *Manager) exportPreparedUser(u *User, userPath string) error {
if err := prepareUserHome(u); err != nil {
return err
}

// 临界区:检查 + Export + 写入 usersMap 原子化,防止并发重复导出
m.usersMapMu.Lock()

// 双检:再次确认未被其他 goroutine 抢先导出
_, alreadyExported = m.usersMap[userPath]
_, alreadyExported := m.usersMap[userPath]
if alreadyExported {
m.usersMapMu.Unlock()
return nil
}

ch := m.userAddedChanMap[u.UserName]

err = m.service.Export(dbus.ObjectPath(userPath), u)
err := m.service.Export(dbus.ObjectPath(userPath), u)
logger.Debugf("export user %q err: %v", userPath, err)

if err == nil {
Expand Down
224 changes: 224 additions & 0 deletions accounts1/ownership_linux.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later

package accounts

import (
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"

"golang.org/x/sys/unix"
)

const maxOwnershipDepth = 128

// homeOwnershipSnapshot holds the account properties used throughout one recovery.
type homeOwnershipSnapshot struct {
userName string
uid string
gid string
path string
}

// Automatic recovery is limited to the account's direct /home child.
func validateAutomaticRecoveryHome(account homeOwnershipSnapshot) error {
name := account.userName
if name == "" || name == "." || name == ".." || strings.ContainsRune(name, '/') || strings.IndexByte(name, 0) >= 0 {
return errors.New("automatic recovery requires a single-component account name")
}
expected := filepath.Join("/home", name)
if strings.TrimRight(account.path, "/") != expected {
return fmt.Errorf("automatic recovery for %q is limited to %q", name, expected)
}
return nil
}

func recoveryIDs(account homeOwnershipSnapshot) (int, int, error) {
parse := func(value, kind string) (int, error) {
id, err := strconv.ParseUint(value, 10, 32)
if err != nil || id == uint64(^uint32(0)) {
return 0, fmt.Errorf("invalid recovery %s %q", kind, value)
}
return int(id), nil
}
uid, err := parse(account.uid, "uid")
if err != nil {
return 0, 0, err
}
gid, err := parse(account.gid, "gid")
return uid, gid, err
}

func openRecoveryHome(home string) (*os.File, error) {
if !filepath.IsAbs(home) || filepath.Clean(home) == "/" {
return nil, fmt.Errorf("invalid recovery home %q", home)
}
fd, err := unix.Open("/", unix.O_PATH|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
if err != nil {
return nil, err
}
for _, name := range strings.Split(strings.TrimPrefix(filepath.Clean(home), "/"), "/") {
next, openErr := unix.Openat(fd, name, unix.O_PATH|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
unix.Close(fd)
if openErr != nil {
return nil, fmt.Errorf("open recovery home %q: %w", home, openErr)
}
fd = next
}
return os.NewFile(uintptr(fd), home), nil
}

// mnt_id is available on the supported 4.19 kernel. Device numbers alone miss
// same-filesystem bind mounts. Failure to identify a mount is not a reason to
// silently allow traversing it.
func recoveryMountID(fd int) (uint64, error) {
data, err := ioutil.ReadFile(fmt.Sprintf("/proc/self/fdinfo/%d", fd))
if err != nil {
return 0, err
}
for _, line := range strings.Split(string(data), "\n") {
fields := strings.Fields(line)
if len(fields) == 2 && fields[0] == "mnt_id:" {
id, err := strconv.ParseUint(fields[1], 10, 64)
if err == nil && id != 0 {
return id, nil
}
return 0, fmt.Errorf("invalid mount identity for fd %d", fd)
}
}
return 0, fmt.Errorf("mount identity unavailable for fd %d", fd)
}

type ownershipRecovery struct {
uid, gid int
mount uint64
chown func(int, int, int) error
}

func chownRecoveryFD(fd, uid, gid int) error {
for {
err := unix.Fchownat(fd, "", uid, gid, unix.AT_EMPTY_PATH|unix.AT_SYMLINK_NOFOLLOW)
if err != unix.EINTR {
return err
}
}
}

func (r *ownershipRecovery) visit(fd int, depth int) error {
if depth > maxOwnershipDepth {
return errors.New("ownership recovery depth limit exceeded")
}
var st unix.Stat_t
if err := unix.Fstat(fd, &st); err != nil {
return err
}
mount, err := recoveryMountID(fd)
if err != nil {
return err
}
if mount != r.mount {
return errors.New("refusing ownership recovery across a mount boundary")
}
switch st.Mode & unix.S_IFMT {
case unix.S_IFDIR:
if err := r.visitChildren(fd, depth); err != nil {
return err
}
case unix.S_IFREG, unix.S_IFLNK:
// An O_PATH|O_NOFOLLOW descriptor pins the link itself. Never recurse
// into its target or reopen any object by its original pathname.
default:
return nil
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
}
// Refresh metadata after processing children and before changing ownership.
if err := unix.Fstat(fd, &st); err != nil {
return err
}
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)
Comment on lines +147 to +150

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

}

func (r *ownershipRecovery) visitChildren(fd, depth int) error {
// '.' resolves inside the pinned directory, even if its original name has
// been moved or replaced. O_PATH itself cannot be used for enumeration.
dirFD, err := unix.Openat(fd, ".", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
if err != nil {
return err
}
dir := os.NewFile(uintptr(dirFD), "ownership-recovery")
defer dir.Close()
for {
names, readErr := dir.Readdirnames(128)
for _, name := range names {
child, err := unix.Openat(dirFD, name, unix.O_PATH|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
if err == unix.ENOENT {
continue
}
if err != nil {
return fmt.Errorf("open recovery entry %q: %w", name, err)
}
err = r.visit(child, depth+1)
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
unix.Close(child)
if err != nil {
return fmt.Errorf("recover entry %q: %w", name, err)
}
Comment on lines +175 to +176

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

}
if readErr == io.EOF {
return nil
}
if readErr != nil {
return readErr
}
}
}

func recoverOwnershipAt(home *os.File, uid, gid int) error {
mount, err := recoveryMountID(int(home.Fd()))
if err != nil {
return err
}
r := ownershipRecovery{uid: uid, gid: gid, mount: mount, chown: chownRecoveryFD}
return r.visit(int(home.Fd()), 0)
}

// prepareRecoveryHome skips optional recovery for an already-owned home. Its
// caller decides whether an error is fatal to an explicit takeover or merely
// diagnostic for ordinary publication.
func prepareRecoveryHome(account homeOwnershipSnapshot, force bool) error {
if err := validateAutomaticRecoveryHome(account); err != nil {
if force {
return err
}
logger.Debugf("skip automatic home recovery for %s: %v", account.userName, err)
return nil
}
uid, gid, err := recoveryIDs(account)
if err != nil {
return err
}
home, err := openRecoveryHome(account.path)
if err != nil {
return err
}
defer home.Close()
var st unix.Stat_t
if err := unix.Fstat(int(home.Fd()), &st); err != nil {
return err
}
if !force && st.Uid == uint32(uid) && st.Gid == uint32(gid) {
return nil
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
}
return recoverOwnershipAt(home, uid, gid)
}
Loading