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..335385814 100644 --- a/accounts1/user_ifc.go +++ b/accounts1/user_ifc.go @@ -1071,16 +1071,50 @@ 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) } 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 } 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