google / xsecurelock

X11 screen lock utility with security in mind
Apache License 2.0
876 stars 65 forks source link

How to auto-set XAUTHORITY=/tmp/xauth_XXXXX created by sddm in systemd unit file? #183

Closed shmilee closed 4 months ago

shmilee commented 5 months ago

I want to use a sleep hook of xsecurelock to auto-lock X before suspend or sleep. But the unit file I used before does not work recently. The file is from ref1 and ref2, like this one. My problem is similar to this issue https://github.com/google/xsecurelock/issues/117. It is caused by the incorrect environment variable XAUTHORITY=/home/%i/.Xauthority which is out-of-date, according to the man of sddm.conf.

xsecurelock[279181]: Invalid MIT-MAGIC-COOKIE-1 key
xsecurelock[279181]:  xsecurelock: Could not connect to $DISPLAY.
# man sddm.conf
The UserAuthFile= option was removed, the file is always created as /tmp/xauth_XXXXX. This is necessary for to the use of FamilyWild entries.

The path of UserAuthFile is easier to get in user session than in systems system slice.

[$] echo $XAUTHORITY
/tmp/xauth_ZtesOe

[$] xauth -v list | head -n1 | cut -d' ' -f4
/tmp/xauth_ZtesOe

At first, I try to figure out how to get user's XAUTHORITY in system service /etc/systemd/system/xsecurelock@.service, but enn... then I find that user service is already aware of XAUTHORITY, and we can call user service in a system sleep service. So a different way to deal with this problem by two unit file is tried, as shown below. A backup url. Another tip: the Type in sleep@.service can be simple or exec, but oneshot and forking will interrupt the sleep process! See more

[$] cat /etc/systemd/system/sleep@.service
# path: /etc/systemd/system/sleep@.service

[Unit]
Description=Call user's sleep service before system suspend/sleep target
Before=sleep.target

[Service]
# oneshot,forking: user unit up, breaks sleep; simple,exec: ok
Type=simple
ExecStart=/usr/bin/systemctl --user --machine=%i@ start --wait xsecurelock.service

[Install]
WantedBy=sleep.target
[$] cat ~/.config/systemd/user/xsecurelock.service
# path: ~/.config/systemd/user/xsecurelock.service

[Unit]
Description=Lock screen before suspend/sleep
Before=sleep.target

[Service]
Type=simple
Environment=XSECURELOCK_FONT="LXGW Neo XiHei Screen"
Environment=XSECURELOCK_SHOW_DATETIME=1
Environment=XSECURELOCK_DATETIME_FORMAT="%%c"
Environment=XSECURELOCK_PASSWORD_PROMPT=time_hex
Environment=XSECURELOCK_NO_COMPOSITE=1
Environment=LC_ALL=zh_CN.UTF-8
ExecStart=/usr/bin/xsecurelock

Although the issue is solved, I still want to know if we can auto-set XAUTHORITY=/tmp/xauth_XXXXX in the system unit file /etc/systemd/system/xsecurelock@.service.

shmilee commented 5 months ago

And, I am not sure if this happens to other display managers those may use libxau or act as X11 root sessions. See: https://github.com/sddm/sddm/issues/1621