Own user accounts and sharing

Two of the panels this desktop still handed to GNOME Settings.

Users manages the account through accountsservice -- the same daemon
GNOME's panel drives, so a name or picture set here is what the login
screen and lock screen read. Name, picture, account type, password,
automatic login, and adding or removing other accounts. Every change is
authorized by polkit through the agent this session already runs; a
dismissed prompt is a normal outcome and says so.

A new password is read from the helper's stdin, hashed by openssl
reading its own stdin, and handed over D-Bus from inside that process.
It is never an argument: argv is world-readable through /proc, so a
password passed that way is published to every process on the machine.
Removing an account takes two presses and says it destroys their files;
the last administrator cannot be removed or demoted, because a machine
nobody can administer is not a state to offer.

Sharing reports what is actually true, including "the software for this
is not installed" -- the honest answer for Samba here, and the case the
panel it replaces shows as a switch that does nothing. Password sign-in
is reported from sshd's configuration rather than assumed: claiming
"keys only" when the file is silent would state a security property that
cannot be backed up.

The Control Center now draws the account's real picture and name. A
generic glyph sat there while a real avatar was already set, which made
the desktop look like it did not know whose it was.

Also here: the KDE Connect contract no longer requires a phone to be
awake. kdeconnectd drops its device objects for a phone it has not seen
recently while the pairing survives in its config, so demanding one
failed whenever the phone was off.

Claude-Session: https://claude.ai/code/session_01BRvzt4H8XXLPVH5MyYdk9L
This commit is contained in:
Gabriel Brown
2026-08-19 13:05:13 -04:00
parent e0c0e53ae0
commit a23b42841a
22 changed files with 1817 additions and 10 deletions
+188
View File
@@ -0,0 +1,188 @@
#!/usr/bin/env python3
"""What this machine offers to other machines, and switches for it.
Every row reports what is actually true, including "the software for this is not
installed". GNOME's Sharing panel shows switches for services that are absent,
which is how a switch ends up doing nothing at all.
Enabling remote login is a system-wide change and goes through pkexec, which
prompts with the polkit agent this desktop already runs. Remote desktop is a
user service and needs no privilege.
panama-sharing snapshot
panama-sharing set-remote-login true|false
panama-sharing set-remote-desktop true|false
panama-sharing set-hostname NAME
"""
from __future__ import annotations
import json
import re
import shutil
import subprocess
import sys
from pathlib import Path
HOSTNAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9-]{0,62}$")
class BoundaryError(RuntimeError):
"""A user-visible validation or permission failure."""
def run(command: list[str], timeout: float = 25.0) -> subprocess.CompletedProcess:
try:
return subprocess.run(command, capture_output=True, text=True,
timeout=timeout, check=False)
except (OSError, subprocess.TimeoutExpired) as error:
raise BoundaryError(f"{command[0]} did not answer.") from error
def unit_state(unit: str, user: bool = False) -> dict:
scope = ["--user"] if user else []
active = run(["systemctl", *scope, "is-active", unit]).stdout.strip()
enabled = run(["systemctl", *scope, "is-enabled", unit]).stdout.strip()
return {
"installed": enabled not in ("", "not-found"),
"active": active == "active",
"enabled": enabled == "enabled",
}
def ssh_setting(name: str) -> str:
"""What sshd's own configuration says, or "" when it says nothing.
`sshd -T` would be authoritative but needs root. Reading the files means
reporting "not configured" rather than guessing a default -- which matters,
because claiming "keys only" on a machine that actually accepts passwords
would be a security claim this cannot back up.
"""
paths = [Path("/etc/ssh/sshd_config")]
paths.extend(sorted(Path("/etc/ssh/sshd_config.d").glob("*.conf"))
if Path("/etc/ssh/sshd_config.d").is_dir() else [])
pattern = re.compile(rf"^\s*{name}\s+(\S+)", re.IGNORECASE)
for path in paths:
try:
for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
found = pattern.match(line)
if found:
return found.group(1)
except OSError:
continue
return ""
def remote_desktop() -> dict:
state = unit_state("gnome-remote-desktop.service", user=True)
state["available"] = bool(shutil.which("grdctl"))
state["rdpEnabled"] = False
state["port"] = ""
state["hasCredentials"] = False
if not state["available"]:
return state
status = run(["grdctl", "status"]).stdout
section = status.split("RDP:", 1)
if len(section) > 1:
block = section[1].split("VNC:", 1)[0]
state["rdpEnabled"] = re.search(r"Status:\s*enabled", block) is not None
port = re.search(r"Port:\s*(\d+)", block)
state["port"] = port.group(1) if port else ""
# grdctl prints "(hidden)" when a credential is stored and nothing when
# it is not, so this reads presence without ever reading the value.
state["hasCredentials"] = "(hidden)" in block
return state
def snapshot() -> dict:
static_name = run(["hostnamectl", "--static"]).stdout.strip()
pretty_name = run(["hostnamectl", "--pretty"]).stdout.strip()
login = unit_state("sshd.service")
login["port"] = ssh_setting("Port") or "22"
login["passwordAuthentication"] = ssh_setting("PasswordAuthentication")
login["rootLogin"] = ssh_setting("PermitRootLogin")
return {
"hostname": static_name,
"prettyHostname": pretty_name,
"remoteLogin": login,
"remoteDesktop": remote_desktop(),
# Reported as absent rather than offered as a switch that would do
# nothing. Installing software is not this page's job.
"fileSharing": {"installed": bool(shutil.which("smbd")), "package": "samba"},
"mediaSharing": {"installed": bool(shutil.which("rygel")), "package": "rygel"},
"error": "",
}
def set_remote_login(enabled: bool) -> None:
if not unit_state("sshd.service")["installed"]:
raise BoundaryError("OpenSSH server is not installed.")
action = ["enable", "--now"] if enabled else ["disable", "--now"]
result = run(["pkexec", "systemctl", *action, "sshd.service"], timeout=120)
if result.returncode != 0:
raise BoundaryError(_refusal(result, "Remote login could not be changed."))
def set_remote_desktop(enabled: bool) -> None:
state = remote_desktop()
if not state["available"]:
raise BoundaryError("Remote desktop support is not installed.")
if enabled and not state["hasCredentials"]:
raise BoundaryError("Set a remote desktop username and password first.")
toggle = run(["grdctl", "rdp", "enable" if enabled else "disable"])
if toggle.returncode != 0:
raise BoundaryError(_refusal(toggle, "Remote desktop could not be changed."))
action = ["enable", "--now"] if enabled else ["disable", "--now"]
result = run(["systemctl", "--user", *action, "gnome-remote-desktop.service"], timeout=60)
if result.returncode != 0:
raise BoundaryError(_refusal(result, "The remote desktop service could not be changed."))
def set_hostname(name: str) -> None:
if not HOSTNAME.fullmatch(name or ""):
raise BoundaryError("A name may use letters, digits and hyphens.")
result = run(["hostnamectl", "set-hostname", name], timeout=60)
if result.returncode != 0:
raise BoundaryError(_refusal(result, "The name could not be changed."))
def _refusal(result: subprocess.CompletedProcess, fallback: str) -> str:
text = (result.stderr or "").strip().splitlines()
if text and ("not authorized" in text[-1].lower() or "dismissed" in text[-1].lower()):
return "That change was not authorized."
return text[-1][:200] if text else fallback
def main(arguments: list[str]) -> int:
try:
if arguments == ["snapshot"]:
print(json.dumps(snapshot(), separators=(",", ":")))
return 0
if len(arguments) == 2 and arguments[0] == "set-remote-login":
set_remote_login(arguments[1] == "true")
elif len(arguments) == 2 and arguments[0] == "set-remote-desktop":
set_remote_desktop(arguments[1] == "true")
elif len(arguments) == 2 and arguments[0] == "set-hostname":
set_hostname(arguments[1])
else:
raise BoundaryError(
"Usage: panama-sharing snapshot | set-remote-login true|false | "
"set-remote-desktop true|false | set-hostname NAME")
except BoundaryError as error:
state = snapshot()
state["error"] = str(error)
print(json.dumps(state, separators=(",", ":")))
return 0
print(json.dumps(snapshot(), separators=(",", ":")))
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))
+272
View File
@@ -0,0 +1,272 @@
#!/usr/bin/env python3
"""User accounts, through accountsservice -- the same daemon GNOME's Users panel
drives.
Everything here that changes something is authorized by polkit, which prompts
through the agent this desktop already runs. This script never asks for a
password itself and never holds an administrator credential.
The one credential it does handle is a NEW password being set. That is read
from stdin, hashed by openssl reading its own stdin, and handed to
accountsservice over D-Bus from inside this process. It is never an argument:
argv is world-readable through /proc, so a password -- or even its hash --
passed that way is published to every process on the machine.
panama-accounts snapshot
panama-accounts set-real-name USER NAME
panama-accounts set-icon USER PATH
panama-accounts set-account-type USER standard|administrator
panama-accounts set-automatic-login USER true|false
panama-accounts set-password USER (new password on stdin)
panama-accounts create-user USERNAME REALNAME standard|administrator
panama-accounts delete-user USERNAME [keep-files|remove-files]
"""
from __future__ import annotations
import json
import os
import re
import subprocess
import sys
ACCOUNTS = "org.freedesktop.Accounts"
ACCOUNTS_PATH = "/org/freedesktop/Accounts"
USER_INTERFACE = "org.freedesktop.Accounts.User"
# Account types as accountsservice numbers them.
STANDARD, ADMINISTRATOR = 0, 1
USERNAME = re.compile(r"^[a-z_][a-z0-9_-]{0,31}$")
class BoundaryError(RuntimeError):
"""A user-visible validation or permission failure."""
def bus():
try:
import gi
gi.require_version("Gio", "2.0")
from gi.repository import Gio, GLib
return Gio, GLib, Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
except Exception as error: # noqa: BLE001 - no bus is a legitimate state
raise BoundaryError("The account service is not answering.") from error
def call(path: str, interface: str, method: str, parameters=None, reply=None):
Gio, GLib, connection = bus()
try:
result = connection.call_sync(
ACCOUNTS, path, interface, method, parameters,
GLib.VariantType(reply) if reply else None,
Gio.DBusCallFlags.NONE, 120000, None)
except Exception as error: # noqa: BLE001
message = str(error)
# Polkit's own refusal is the common case and deserves plain words
# rather than a D-Bus error string.
if "not authorized" in message.lower() or "dismissed" in message.lower():
raise BoundaryError("That change was not authorized.") from error
raise BoundaryError(_clean(message)) from error
return result.unpack() if result is not None else None
def _clean(message: str) -> str:
"""The last useful sentence of a D-Bus error, without the type prefix."""
trimmed = re.sub(r"^GDBus\.Error:[^:]+:\s*", "", message).strip()
return trimmed.splitlines()[0][:200] if trimmed else "That change failed."
def properties(path: str) -> dict:
Gio, GLib, connection = bus()
result = connection.call_sync(
ACCOUNTS, path, "org.freedesktop.DBus.Properties", "GetAll",
GLib.Variant("(s)", (USER_INTERFACE,)), GLib.VariantType("(a{sv})"),
Gio.DBusCallFlags.NONE, 20000, None)
return result.unpack()[0]
def user_path(username: str) -> str:
if not USERNAME.fullmatch(username or ""):
raise BoundaryError("That is not a user name.")
from gi.repository import GLib
return call(ACCOUNTS_PATH, ACCOUNTS, "FindUserByName",
GLib.Variant("(s)", (username,)), "(o)")[0]
def describe(path: str) -> dict:
values = properties(path)
icon = str(values.get("IconFile") or "")
return {
"path": path,
"userName": str(values.get("UserName") or ""),
"realName": str(values.get("RealName") or ""),
# Reported only when it is actually there: accountsservice keeps the
# path in its database whether or not a file exists, so a deleted
# avatar otherwise shows as a broken image.
"iconFile": icon if icon and os.path.isfile(icon) else "",
"administrator": int(values.get("AccountType") or 0) == ADMINISTRATOR,
"locked": bool(values.get("Locked")),
"automaticLogin": bool(values.get("AutomaticLogin")),
"loginTime": int(values.get("LoginTime") or 0),
"shell": str(values.get("Shell") or ""),
"homeDirectory": str(values.get("HomeDirectory") or ""),
"systemAccount": bool(values.get("SystemAccount")),
"uid": int(values.get("Uid") or 0),
}
def snapshot() -> dict:
paths = call(ACCOUNTS_PATH, ACCOUNTS, "ListCachedUsers", None, "(ao)")[0]
users = [describe(path) for path in paths]
users = [user for user in users if not user["systemAccount"]]
users.sort(key=lambda user: user["uid"])
me = os.environ.get("USER") or ""
return {
"users": users,
"currentUser": me,
# Removing the only administrator would leave a machine nobody can
# administer, so the page needs to know rather than find out.
"administratorCount": sum(1 for user in users if user["administrator"]),
"error": "",
}
def set_real_name(username: str, name: str) -> None:
from gi.repository import GLib
if len(name) > 128 or "\n" in name or ":" in name:
raise BoundaryError("That name cannot be used.")
call(user_path(username), USER_INTERFACE, "SetRealName",
GLib.Variant("(s)", (name,)))
def set_icon(username: str, path: str) -> None:
from gi.repository import GLib
if not os.path.isfile(path):
raise BoundaryError("That picture no longer exists.")
call(user_path(username), USER_INTERFACE, "SetIconFile",
GLib.Variant("(s)", (path,)))
def set_account_type(username: str, kind: str) -> None:
from gi.repository import GLib
if kind not in ("standard", "administrator"):
raise BoundaryError("That is not an account type.")
call(user_path(username), USER_INTERFACE, "SetAccountType",
GLib.Variant("(i)", (ADMINISTRATOR if kind == "administrator" else STANDARD,)))
def set_automatic_login(username: str, enabled: bool) -> None:
from gi.repository import GLib
call(user_path(username), USER_INTERFACE, "SetAutomaticLogin",
GLib.Variant("(b)", (enabled,)))
def set_password(username: str) -> None:
"""Set a new password, read from stdin and never named on a command line."""
secret = sys.stdin.buffer.read()
# A trailing newline from a pipe is not part of the password.
if secret.endswith(b"\n"):
secret = secret[:-1]
if not secret:
raise BoundaryError("No password was provided.")
if len(secret) < 6:
raise BoundaryError("That password is too short.")
# openssl reads the password on ITS stdin too, so the cleartext never
# appears in a process listing at any point in the chain.
hashed = subprocess.run(["openssl", "passwd", "-6", "-stdin"],
input=secret, capture_output=True, timeout=30, check=False)
if hashed.returncode != 0 or not hashed.stdout.strip():
raise BoundaryError("The password could not be prepared.")
from gi.repository import GLib
call(user_path(username), USER_INTERFACE, "SetPassword",
GLib.Variant("(ss)", (hashed.stdout.decode().strip(), "")))
def create_user(username: str, real_name: str, kind: str) -> None:
from gi.repository import GLib
if not USERNAME.fullmatch(username or ""):
raise BoundaryError("A user name may use lowercase letters, digits, - and _.")
if kind not in ("standard", "administrator"):
raise BoundaryError("That is not an account type.")
call(ACCOUNTS_PATH, ACCOUNTS, "CreateUser",
GLib.Variant("(ssi)", (username, real_name,
ADMINISTRATOR if kind == "administrator" else STANDARD)),
"(o)")
def delete_user(username: str, files: str) -> None:
from gi.repository import GLib
if files not in ("keep-files", "remove-files"):
raise BoundaryError("Say whether to keep or remove the home directory.")
if username == (os.environ.get("USER") or ""):
raise BoundaryError("You cannot delete the account you are signed in to.")
state = snapshot()
target = next((user for user in state["users"] if user["userName"] == username), None)
if target is None:
raise BoundaryError("That account no longer exists.")
if target["administrator"] and state["administratorCount"] <= 1:
raise BoundaryError("That is the only administrator; the machine would have none.")
call(ACCOUNTS_PATH, ACCOUNTS, "DeleteUser",
GLib.Variant("(xb)", (target["uid"], files == "remove-files")))
def main(arguments: list[str]) -> int:
try:
if arguments == ["snapshot"]:
print(json.dumps(snapshot(), separators=(",", ":")))
return 0
if len(arguments) == 3 and arguments[0] == "set-real-name":
set_real_name(arguments[1], arguments[2])
elif len(arguments) == 3 and arguments[0] == "set-icon":
set_icon(arguments[1], arguments[2])
elif len(arguments) == 3 and arguments[0] == "set-account-type":
set_account_type(arguments[1], arguments[2])
elif len(arguments) == 3 and arguments[0] == "set-automatic-login":
set_automatic_login(arguments[1], arguments[2] == "true")
elif len(arguments) == 2 and arguments[0] == "set-password":
set_password(arguments[1])
elif len(arguments) == 4 and arguments[0] == "create-user":
create_user(arguments[1], arguments[2], arguments[3])
elif len(arguments) == 3 and arguments[0] == "delete-user":
delete_user(arguments[1], arguments[2])
else:
raise BoundaryError(
"Usage: panama-accounts snapshot | set-real-name USER NAME | "
"set-icon USER PATH | set-account-type USER standard|administrator | "
"set-automatic-login USER true|false | set-password USER | "
"create-user USERNAME REALNAME standard|administrator | "
"delete-user USERNAME keep-files|remove-files")
except BoundaryError as error:
# Answers with the fresh state plus the message, so a page never has to
# ask twice to find out what happened.
try:
state = snapshot()
except BoundaryError:
state = {"users": [], "currentUser": "", "administratorCount": 0}
state["error"] = str(error)
print(json.dumps(state, separators=(",", ":")))
return 0
print(json.dumps(snapshot(), separators=(",", ":")))
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))