From 1c76b85a61deabad9fb2908bfaece92bd44f81c7 Mon Sep 17 00:00:00 2001 From: fuleyi Date: Thu, 12 Nov 2026 21:38:02 +0800 Subject: [PATCH 1/3] fix: authorize password hint writes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. SetPasswordHint took no sender and performed no authorization, so any local user could rewrite another account's password hint. The hint is shown before authentication, so a cross-user write can mislead whoever is recovering that account. 2. The method now takes a sender and authorizes it: the account owner passes with the change-own-data action without a prompt, other callers need user-administration. The greeter, which saves the hint after a password change for the selected user, runs as lightdm and is already granted user-administration in an active session by the existing polkit rule, so that path keeps working. 3. Validate the hint as well: at most 512 characters and no control characters, so a caller cannot write an oversized or multi-line value into the user config file. An empty hint still clears the old one. 4. Hold PropsMu across the config write and property update. The config writer snapshots in-memory fields such as Layout, so releasing the config-file lock before updating PasswordHint could allow a concurrent SetLayout to persist a stale layout or leave the file and property describing different values. fix: 密码提示写入补鉴权、入参校验与并发保护 1. SetPasswordHint 既不接收 sender 也不鉴权,任意本地用户可改写他人的 密码提示;提示会在认证前展示,被篡改后会误导正在找回账号的用户。 2. 方法现在接收 sender 并鉴权:账号本人在自己对象上免认证 (change-own-user-data),其他人需要 user-administration。登录界面 在改密后保存提示、以 lightdm 运行,既有 polkit 规则已对活跃会话放行 user-administration,该路径不受影响。 3. 同时校验入参:最长 512 字符且不允许控制字符,避免把超长或多行内容 写进用户配置文件;空字符串仍按原语义清空提示。 4. 配置写入和属性更新统一持有 PropsMu。配置写入会快照 Layout 等内存 字段,若在更新 PasswordHint 前释放锁,并发的 SetLayout 可能把旧 layout 写回,或导致配置文件与 D-Bus 属性不一致。 Log: 用户只能修改自己的密码提示;他人修改需要管理员认证;并发修改不再把旧设置写回。 Influence: 1) 用户 A 对用户 B 的 User 对象调用 SetPasswordHint 应返回授权错误,B 的提示不变;2) 用户 A 修改自己的提示应免弹窗成功,空字符串应清空提示;3) 在登录界面修改密码后保存提示仍应成功,不弹认证框;4) 超过 512 字符或含换行/制表符等控制字符的提示应被拒绝,配置文件不变;5) 并发修改提示或同时修改 Layout 时,配置文件与属性保持一致。 PMS: BUG-379743 (cherry picked from commit f394c55b6a6dbe0fbe866eef17b8d8d9e0595537) --- accounts1/password_hint.go | 28 +++++++++++++++++++++ accounts1/password_hint_test.go | 43 +++++++++++++++++++++++++++++++++ accounts1/user_ifc.go | 28 +++++++++++++++++++-- 3 files changed, 97 insertions(+), 2 deletions(-) create mode 100644 accounts1/password_hint.go create mode 100644 accounts1/password_hint_test.go diff --git a/accounts1/password_hint.go b/accounts1/password_hint.go new file mode 100644 index 000000000..de5adda57 --- /dev/null +++ b/accounts1/password_hint.go @@ -0,0 +1,28 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +package accounts + +import ( + "errors" + "fmt" + "unicode/utf8" +) + +// maxPasswordHintLength bounds what can be written into the user config file. +const maxPasswordHintLength = 512 + +// validatePasswordHint rejects hints that would not round-trip through the +// user config file: too long, or containing control characters. +func validatePasswordHint(hint string) error { + if utf8.RuneCountInString(hint) > maxPasswordHintLength { + return fmt.Errorf("password hint exceeds %d characters", maxPasswordHintLength) + } + for _, r := range hint { + if r < 0x20 || r == 0x7f { + return errors.New("password hint contains control characters") + } + } + return nil +} diff --git a/accounts1/password_hint_test.go b/accounts1/password_hint_test.go new file mode 100644 index 000000000..69dc53b17 --- /dev/null +++ b/accounts1/password_hint_test.go @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +package accounts + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestValidatePasswordHint(t *testing.T) { + tests := []struct { + name string + hint string + wantErr bool + }{ + {"empty is allowed and clears the hint", "", false}, + {"plain text", "my first pet", false}, + {"chinese text", "第一只宠物的名字", false}, + {"at the limit", strings.Repeat("a", maxPasswordHintLength), false}, + {"over the limit", strings.Repeat("a", maxPasswordHintLength+1), true}, + {"multi-byte counted in characters", strings.Repeat("密", maxPasswordHintLength), false}, + {"newline", "a\nb", true}, + {"carriage return", "a\rb", true}, + {"tab", "a\tb", true}, + {"del", "a\x7fb", true}, + {"nul", "a\x00b", true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := validatePasswordHint(tt.hint) + if tt.wantErr { + assert.Error(t, err) + } else { + assert.NoError(t, err) + } + }) + } +} diff --git a/accounts1/user_ifc.go b/accounts1/user_ifc.go index 0295ef2da..eea7931ec 100644 --- a/accounts1/user_ifc.go +++ b/accounts1/user_ifc.go @@ -1071,9 +1071,33 @@ func (u *User) PasswordExpiredInfo() (expiredStatus ExpiredStatus, dayLeft int64 return expiredStatusNormal, daysLeft + 1, nil } -func (u *User) SetPasswordHint(hint string) (busErr *dbus.Error) { +func (u *User) SetPasswordHint(sender dbus.Sender, hint string) (busErr *dbus.Error) { + // The hint belongs to a single account but the object path is public, so + // without this check any local user could rewrite someone else's hint. + // The owner passes without a prompt; other callers need the + // user-administration action, which the polkit rule grants to the + // greeter's lightdm user in an active session. + err := u.checkAuth(sender, true, polkitActionChangeOwnData) + if err != nil { + logger.Warningf("SetPasswordHint denied for %v: %v", sender, err) + return dbusutil.ToError(err) + } + + err = validatePasswordHint(hint) + if err != nil { + return dbusutil.ToError(err) + } + + // Hold PropsMu across the config write and the exported property update. + // writeUserConfigWithChanges snapshots other in-memory fields (for example + // Layout), so releasing the config-file lock before updating PasswordHint + // could let SetLayout persist a stale layout or leave the file and the + // D-Bus property describing different values. + u.PropsMu.Lock() + defer u.PropsMu.Unlock() + encodeHint := base64.StdEncoding.EncodeToString([]byte(hint)) - err := u.writeUserConfigWithChange(confKeyPasswordHint, encodeHint) + err = u.writeUserConfigWithChange(confKeyPasswordHint, encodeHint) if err == nil { u.setPropPasswordHint(hint) } From 066a601abf90b48222b36ecb0a6bd89d083baa6e Mon Sep 17 00:00:00 2001 From: fuleyi Date: Thu, 12 Nov 2026 21:39:23 +0800 Subject: [PATCH 2/3] fix: authorize GetReminderInfo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. GetReminderInfo returned the account's login statistics to any caller: last and current login time, terminal, source address, the number of failed logins since the last successful one, and the shadow ageing fields. Nothing in the method checked who asked. 2. It now takes the caller's sender and authorizes it: the account owner passes with the change-own-data action without a prompt, other callers need user-administration. The legitimate consumer, dde-login-reminder, queries its own uid's User object at login, so it keeps working without a prompt. fix: 登录提醒信息补鉴权 1. GetReminderInfo 把登录统计返回给任何调用者:上次与本次登录时间、 终端、来源地址、上次成功登录以来的失败次数,以及 shadow 老化字段, 方法内没有任何调用者检查。 2. 现在接收 sender 并鉴权:账号本人在自己对象上免认证 (change-own-user-data),其他人需要 user-administration。合法调用方 dde-login-reminder 在登录后查询的是自己 uid 对应的 User 对象,仍可 免弹窗获取。 Log: 登录记录与失败次数只对账号本人或管理员可见。 Influence: 1) 用户 A 对用户 B 的 User 对象调用 GetReminderInfo 应返回授权错误,不返回任何登录记录;2) 用户 A 查询自己的提醒信息应免弹窗成功,登录后 dde-login-reminder 仍能弹出提醒;3) 管理员通过 polkit 认证后可查询他人信息;4) 被拒时不应读取 shadow 与 wtmp/btmp。 PMS: BUG-379743 (cherry picked from commit e9f8199921851622708b08e4b4435a393eabb59e) --- accounts1/user_ifc.go | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/accounts1/user_ifc.go b/accounts1/user_ifc.go index eea7931ec..335385814 100644 --- a/accounts1/user_ifc.go +++ b/accounts1/user_ifc.go @@ -1104,7 +1104,17 @@ func (u *User) SetPasswordHint(sender dbus.Sender, hint string) (busErr *dbus.Er return dbusutil.ToError(err) } -func (u *User) GetReminderInfo() (info LoginReminderInfo, dbusErr *dbus.Error) { +// GetReminderInfo returns login statistics and shadow ageing fields for this +// account. It exposes when the account last logged in, from where, and how +// many failed attempts there were, so it must not be readable by every local +// user: the owner passes without a prompt, other callers need the +// user-administration action. +func (u *User) GetReminderInfo(sender dbus.Sender) (info LoginReminderInfo, dbusErr *dbus.Error) { + err := u.checkAuth(sender, true, polkitActionChangeOwnData) + if err != nil { + logger.Warningf("GetReminderInfo denied for %v: %v", sender, err) + return info, dbusutil.ToError(err) + } return getLoginReminderInfo(u.UserName), nil } From 6e0a362d71d97c4faf6376990f773fdde44e0f1d Mon Sep 17 00:00:00 2001 From: fuleyi Date: Tue, 17 Nov 2026 17:57:24 +0800 Subject: [PATCH 3/3] fix: authorize greeter theme updates with polkit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Reuse greeter.doAction and make lightdm its action owner so the unprivileged service can check callers of other identities. 2. Allow active local sessions without authentication; remote, inactive and sessionless callers fall back to allow_any=no. 3. Keep FD cleanup on rejection, serialize theme and xsettings updates, and reject theme values that could inject extra xsettingsd keys. fix: 使用 polkit 鉴权登录界面主题更新 1. 复用 greeter.doAction,并将 lightdm 设为 action owner,使非 root 服务可以代查其他身份的调用者。 2. 本地活跃会话免认证;远程、非活跃与无会话调用落到 allow_any=no。 3. 拒绝时关闭调用方 FD,主题与 xsettings 更新串行化,并拒绝可能注入 额外 xsettingsd 键的主题值。 Log: 本地活跃会话可免认证更新共享登录界面主题,远程与无会话调用被拒绝 Influence: 1. 桌面会话内更新主题无需认证弹窗,qt-theme.ini 与 xsettingsd.conf 正确刷新 2. SSH 或远程调用返回 access denied,两份配置保持不变 3. 鉴权失败与 polkit 不可用时调用返回错误且不泄漏 FD PMS: BUG-379743 (cherry picked from commit def84cf4f61494201cb6333fa000cf605bc5bf06) --- bin/dde-greeter-setter/manager.go | 136 +++++++++++++----- bin/dde-greeter-setter/manager_test.go | 82 ++++++++++- .../org.deepin.dde.greeter.policy | 3 +- 3 files changed, 185 insertions(+), 36 deletions(-) diff --git a/bin/dde-greeter-setter/manager.go b/bin/dde-greeter-setter/manager.go index 33091a29d..407efbd9e 100644 --- a/bin/dde-greeter-setter/manager.go +++ b/bin/dde-greeter-setter/manager.go @@ -1,17 +1,21 @@ -// SPDX-FileCopyrightText: 2018 - 2022 UnionTech Software Technology Co., Ltd. +// SPDX-FileCopyrightText: 2018 - 2026 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later package main import ( + "errors" "fmt" "io" "os" "regexp" "strconv" + "sync" + "syscall" "github.com/godbus/dbus/v5" + polkit "github.com/linuxdeepin/go-dbus-factory/system/org.freedesktop.policykit1" "github.com/linuxdeepin/go-lib/dbusutil" "github.com/linuxdeepin/go-lib/keyfile" ) @@ -22,6 +26,8 @@ const ( dbusServiceName = "org.deepin.dde.Greeter1" dbusPath = "/org/deepin/dde/Greeter1" dbusInterface = dbusServiceName + + polkitActionGreeter = "org.deepin.dde.greeter.doAction" ) const ( @@ -56,18 +62,64 @@ type Manager struct { service *dbusutil.Service } +var greeterThemeMu sync.Mutex + +func closeUnixFD(fd dbus.UnixFD) { + if fd < 0 { + return + } + _ = syscall.Close(int(fd)) +} + func (m *Manager) UpdateGreeterQtTheme(sender dbus.Sender, fd dbus.UnixFD) *dbus.Error { - m.service.DelayAutoQuit() - err := updateGreeterQtTheme(fd) + // The lightdm service owns this Polkit action, so it can check the + // caller's authorization even when the caller has a different UID. + authority := polkit.NewAuthority(m.service.Conn()) + subject := polkit.MakeSubject(polkit.SubjectKindSystemBusName) + subject.SetDetail("name", string(sender)) + result, err := authority.CheckAuthorization(0, subject, polkitActionGreeter, + nil, polkit.CheckAuthorizationFlagsAllowUserInteraction, "") if err != nil { + // Keep the underlying failure in the journal, but do not expose + // polkit internals to the caller: both an unreachable authority + // and a denied request are reported as access denied. + closeUnixFD(fd) + logger.Warningf("failed to authorize %v: %v", sender, err) + return dbusutil.ToError(errAccessDenied) + } + if !result.IsAuthorized { + closeUnixFD(fd) + logger.Warningf("caller %v is not authorized for %s", sender, polkitActionGreeter) + return dbusutil.ToError(errAccessDenied) + } + + m.service.DelayAutoQuit() + + // The theme file and xsettingsd.conf must be replaced as one logical + // update. Serialize the complete replacement; otherwise two authorized + // callers can interleave the fixed .tmp file and leave the two files + // describing different themes. + greeterThemeMu.Lock() + defer greeterThemeMu.Unlock() + + if err := updateGreeterQtTheme(fd); err != nil { logger.Warning(err) + return dbusutil.ToError(err) } - updateXSettingsConfig() - return dbusutil.ToError(err) + if err := updateXSettingsConfig(); err != nil { + logger.Warning(err) + return dbusutil.ToError(err) + } + return nil } +var errAccessDenied = errors.New("access denied") + func updateGreeterQtTheme(fd dbus.UnixFD) error { f := os.NewFile(uintptr(fd), "") + if f == nil { + return fmt.Errorf("invalid file descriptor %d", fd) + } defer f.Close() // 目录创建由 postinst 脚本处理,这里只负责文件写入 @@ -96,19 +148,20 @@ func updateGreeterQtTheme(fd dbus.UnixFD) error { return err } -func updateXSettingsConfig() { +func updateXSettingsConfig() error { + return updateXSettingsConfigFiles(themeFile, xsettingsFile) +} + +func updateXSettingsConfigFiles(themePath, xsettingsPath string) error { kf := keyfile.NewKeyFile() - err := kf.LoadFromFile(themeFile) - if err != nil { - logger.Warning(err) - return + if err := kf.LoadFromFile(themePath); err != nil { + return fmt.Errorf("load greeter theme %q: %w", themePath, err) } // 目录创建由 postinst 脚本处理,这里只负责文件写入 - xf, err := os.OpenFile(xsettingsFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) + xf, err := os.OpenFile(xsettingsPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { - logger.Warning(err) - return + return fmt.Errorf("open xsettings file %q: %w", xsettingsPath, err) } defer xf.Close() @@ -117,44 +170,59 @@ func updateXSettingsConfig() { value, err := kf.GetString(themeSection, themeKey) if err == nil { if isInteger(value) { - _, err = xf.WriteString(fmt.Sprintf("%s %s\n", xsettingsKey, value)) + if _, err = xf.WriteString(fmt.Sprintf("%s %s\n", xsettingsKey, value)); err != nil { + return fmt.Errorf("write xsettings key %s: %w", xsettingsKey, err) + } + } else if quoteXSettingsValue(value) == "" && value != "" { + // The value comes from a file the caller controls. A quote or + // newline inside it would otherwise terminate the string and + // inject extra xsettingsd keys, so such values are dropped. + logger.Warningf("skip invalid xsettings value for %s", xsettingsKey) } else { - _, err = xf.WriteString(fmt.Sprintf("%s \"%s\"\n", xsettingsKey, value)) + if _, err = xf.WriteString(fmt.Sprintf("%s %s\n", xsettingsKey, quoteXSettingsValue(value))); err != nil { + return fmt.Errorf("write xsettings key %s: %w", xsettingsKey, err) + } } - } - - if err != nil { - logger.Warning(err) + } else { + logger.Debugf("greeter theme key %s is absent: %v", themeKey, err) } } // 换算缩放 xsettingsKeyDpi = themeKeyScreenScaleFactors * themeKeyScaleLogicalDpi * 1024 themeDpiStr, err := kf.GetString(themeSection, themeKeyScaleLogicalDpi) if err != nil { - logger.Warningf("cannot get DPI: %v", err) - return - } - exp, err := regexp.Compile(`^([0-9]+),([0-9]+)$`) - if err != nil { - logger.Warning(err) - return + return fmt.Errorf("read greeter DPI: %w", err) } + exp := regexp.MustCompile(`^([0-9]+),([0-9]+)$`) substr := exp.FindStringSubmatch(themeDpiStr) - if len(substr) < 2 { - logger.Warning("cannot parse theme dpi") - return + if len(substr) < 3 { + return fmt.Errorf("parse greeter DPI %q", themeDpiStr) } themeDpi, err := strconv.ParseUint(substr[1], 10, 32) if err != nil { - logger.Warning(err) - return + return fmt.Errorf("parse greeter DPI value %q: %w", substr[1], err) } scale, err := kf.GetFloat64(themeSection, themeKeyScreenScaleFactors) - xDpi := uint64(scale * float64(themeDpi) * 1024) - _, err = xf.WriteString(fmt.Sprintf("%s %d\n", xsettingsKeyDpi, xDpi)) if err != nil { - logger.Warning(err) + return fmt.Errorf("read greeter scale factors: %w", err) + } + xDpi := uint64(scale * float64(themeDpi) * 1024) + if _, err = xf.WriteString(fmt.Sprintf("%s %d\n", xsettingsKeyDpi, xDpi)); err != nil { + return fmt.Errorf("write xsettings DPI: %w", err) + } + return nil +} + +// quoteXSettingsValue renders value as an xsettingsd string. Values that +// cannot be rendered safely (quotes, backslashes, control characters) yield +// an empty string and must be skipped by the caller. +func quoteXSettingsValue(value string) string { + for _, r := range value { + if r == '"' || r == '\\' || r < 0x20 || r == 0x7f { + return "" + } } + return `"` + value + `"` } func (*Manager) GetInterfaceName() string { diff --git a/bin/dde-greeter-setter/manager_test.go b/bin/dde-greeter-setter/manager_test.go index 0f9c4b91f..3bcfda1a9 100644 --- a/bin/dde-greeter-setter/manager_test.go +++ b/bin/dde-greeter-setter/manager_test.go @@ -1,10 +1,12 @@ -// SPDX-FileCopyrightText: 2018 - 2022 UnionTech Software Technology Co., Ltd. +// SPDX-FileCopyrightText: 2018 - 2026 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later package main import ( + "os" + "path/filepath" "testing" "github.com/stretchr/testify/assert" @@ -46,3 +48,81 @@ func Test_isInteger(t *testing.T) { }) } } + +func Test_quoteXSettingsValue(t *testing.T) { + tests := []struct { + name string + value string + want string + }{ + {"plain name", "Noto Sans", `"Noto Sans"`}, + {"empty", "", `""`}, + {"quote cannot terminate the string", `a"b`, ""}, + {"backslash cannot escape the quote", `a\"b`, ""}, + {"newline cannot inject a key", "a\nNet/IconThemeName \"x\"", ""}, + {"carriage return", "a\rb", ""}, + {"tab", "a\tb", ""}, + {"del", "a\x7fb", ""}, + {"unicode is preserved", "文泉驿", `"文泉驿"`}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, quoteXSettingsValue(tt.value)) + }) + } +} + +func Test_updateXSettingsConfigInjectionBlocked(t *testing.T) { + dir := t.TempDir() + themePath := filepath.Join(dir, "qt-theme.ini") + xsettingsPath := filepath.Join(dir, "xsettingsd.conf") + + // The Font value contains a quote followed by a complete injected key. + // updateXSettingsConfig must skip this value instead of rendering it. + theme := `[Theme] +IconThemeName=Adwaita +FontSize=10 +Font=Noto Sans" Net/IconThemeName "attacker +MonoFont=Noto Mono +ScreenScaleFactors=1 +ScaleLogicalDpi=96,96 +` + assert.NoError(t, os.WriteFile(themePath, []byte(theme), 0600)) + + assert.NoError(t, updateXSettingsConfigFiles(themePath, xsettingsPath)) + got, err := os.ReadFile(xsettingsPath) + assert.NoError(t, err) + assert.NotContains(t, string(got), `Net/IconThemeName "attacker"`) + assert.Contains(t, string(got), `Net/IconThemeName "Adwaita"`) +} + +func Test_updateXSettingsConfigMissingDPI(t *testing.T) { + dir := t.TempDir() + themePath := filepath.Join(dir, "qt-theme.ini") + xsettingsPath := filepath.Join(dir, "xsettingsd.conf") + + theme := `[Theme] +IconThemeName=Adwaita +FontSize=10 +` + assert.NoError(t, os.WriteFile(themePath, []byte(theme), 0600)) + assert.Error(t, updateXSettingsConfigFiles(themePath, xsettingsPath)) +} + +func Test_updateXSettingsConfigOptionalKeys(t *testing.T) { + dir := t.TempDir() + themePath := filepath.Join(dir, "qt-theme.ini") + xsettingsPath := filepath.Join(dir, "xsettingsd.conf") + + theme := `[Theme] +IconThemeName=Adwaita +ScreenScaleFactors=1 +ScaleLogicalDpi=96,96 +` + assert.NoError(t, os.WriteFile(themePath, []byte(theme), 0600)) + assert.NoError(t, updateXSettingsConfigFiles(themePath, xsettingsPath)) + got, err := os.ReadFile(xsettingsPath) + assert.NoError(t, err) + assert.Contains(t, string(got), `Net/IconThemeName "Adwaita"`) +} diff --git a/misc/polkit-action/org.deepin.dde.greeter.policy b/misc/polkit-action/org.deepin.dde.greeter.policy index 3956e133b..f8bbf3c2b 100644 --- a/misc/polkit-action/org.deepin.dde.greeter.policy +++ b/misc/polkit-action/org.deepin.dde.greeter.policy @@ -10,8 +10,9 @@ no no - auth_admin + yes + unix-user:lightdm Check Authentication Authentication is required to perform this action Check Authentication