Skip to content

guardian_daemon

Modules:

  • config

    Configuration management for the Guardian Daemon.

  • enforcer

    Enforcement module for guardian-daemon.

  • ipc

    IPC server for admin commands of the Guardian Daemon.

  • logging

    Guardian logging setup module.

  • policy

    Policy loader for guardian-daemon.

  • sessions

    Session tracking for guardian-daemon.

  • storage

    Central SQLite interface for guardian-daemon.

  • systemd_manager

    Systemd manager for guardian-daemon.

  • user_manager

    User manager for guardian-daemon.

config

Configuration management for the Guardian Daemon.

Classes:

  • Config

    Handles loading, merging, and validating the daemon's configuration.

  • ConfigError

    Custom exception for configuration errors.

Config

Config(config_dir=None)

Handles loading, merging, and validating the daemon's configuration.

Methods:

  • get

    Gets a configuration value.

get

get(key, default=None)

Gets a configuration value.

ConfigError

Bases: Exception

Custom exception for configuration errors.

enforcer

Enforcement module for guardian-daemon. Checks quota and curfew, enforces limits by terminating sessions and blocking logins.

Classes:

  • Enforcer

    Enforcement logic for quota and curfew. Handles session termination and user notifications.

Enforcer

Enforcer(policy: Policy, tracker: SessionTracker)

Enforcement logic for quota and curfew. Handles session termination and user notifications.

Methods:

  • enforce_user

    Checks quota and curfew for a user and enforces actions if necessary.

  • handle_grace_period

    Handles the grace period by notifying the user every minute until time is up.

  • notify_user

    Sends a desktop notification to all matching agents of the given user (via D-Bus).

  • terminate_session

    Terminates all running desktop sessions of the user (via systemd loginctl).

enforce_user async

enforce_user(username)

Checks quota and curfew for a user and enforces actions if necessary.

handle_grace_period async

handle_grace_period(username)

Handles the grace period by notifying the user every minute until time is up.

notify_user async

notify_user(username, message, category='info')

Sends a desktop notification to all matching agents of the given user (via D-Bus).

terminate_session async

terminate_session(username)

Terminates all running desktop sessions of the user (via systemd loginctl). Only sessions with a desktop environment (not systemd-user/service) are targeted.

ipc

IPC server for admin commands of the Guardian Daemon.

Classes:

GuardianIPCServer

GuardianIPCServer(
    config, tracker: SessionTracker, policy: Policy
)

IPC server for admin commands of the Guardian Daemon. Provides a socket interface for status and control commands.

Parameters:

  • config

    (dict) –

    Configuration data

  • tracker

    (SessionTracker) –

    The main session tracker instance.

  • policy

    (Policy) –

    The main policy instance.

Methods:

close

close()

Closes the IPC socket and removes the socket file.

handle_connection async

handle_connection(reader, writer)

Handles an incoming client connection.

handle_describe_commands

handle_describe_commands(_)

Returns a description of all available IPC commands and their parameters as JSON.

handle_get_curfew

handle_get_curfew(kid)

Returns the current curfew times of a kid.

Parameters:

  • kid
    (str) –

    Username

handle_get_quota async

handle_get_quota(kid)

Returns the current quota status of a kid.

Parameters:

  • kid
    (str) –

    Username

handle_list_kids

handle_list_kids(_)

Returns the list of all kids (users).

handle_list_timers

handle_list_timers(_)

Lists all active Guardian timers.

handle_reload_timers

handle_reload_timers(_)

Reloads the timer configuration.

handle_reset_quota async

handle_reset_quota(_)

Resets the daily quota for all users (deletes sessions since last reset).

start async

start()

Starts the IPC server.

logging

Guardian logging setup module. Configures log level, format, and target based on the application config.

Functions:

  • get_logger

    Returns a configured structlog logger instance.

  • setup_logging

    Sets up structlog and stdlib logging according to the provided config.

get_logger

get_logger(name)

Returns a configured structlog logger instance. Ensures that setup_logging() has been called before returning a logger.

setup_logging

setup_logging(config)

Sets up structlog and stdlib logging according to the provided config. This function should only be called once at application startup.

policy

Policy loader for guardian-daemon. Loads and validates settings from a YAML configuration file.

Classes:

Policy

Policy(
    config_path: Optional[str] = None,
    db_path: Optional[str] = None,
)

Parameters:

  • config_path

    (str, default: None ) –

    Path to the YAML configuration file.

  • db_path

    (str, default: None ) –

    Path to the SQLite database.

Methods:

  • get_default

    Return a default value from the policy.

  • get_timezone

    Return the configured timezone.

  • get_user_policy

    Return the policy settings for a specific user.

  • reload

    Reload the policy configuration and synchronize with the database.

get_default

get_default(key: str) -> Any

Return a default value from the policy.

Parameters:

  • key
    (str) –

    Name of the default key

Returns:

  • Any ( Any ) –

    The default value or None

get_timezone

get_timezone() -> str

Return the configured timezone.

Returns:

  • str ( str ) –

    Timezone (e.g. "Europe/Berlin")

get_user_policy

get_user_policy(username: str) -> Optional[Dict[str, Any]]

Return the policy settings for a specific user.

Parameters:

  • username
    (str) –

    Username

Returns:

  • Optional[Dict[str, Any]]

    dict | None: The user's settings or None if not present.

reload

reload()

Reload the policy configuration and synchronize with the database.

sessions

Session tracking for guardian-daemon. Monitors logins/logouts via systemd-logind (DBus), measures usage time and checks quota/curfew. Stores data in SQLite.

Classes:

GuardianDaemonInterface

GuardianDaemonInterface(session_tracker)

Bases: ServiceInterface

Methods:

  • LockEvent

    Receives lock/unlock events from agents and forwards to SessionTracker.

LockEvent async

LockEvent(
    session_id: s, username: s, locked: b, timestamp: d
)

Receives lock/unlock events from agents and forwards to SessionTracker.

SessionTracker

SessionTracker(
    policy: Policy, config: dict, user_manager: UserManager
)

Monitors and stores user sessions, checks quota and curfew. Connects to systemd-logind via DBus.

Parameters:

  • policy

    (Policy) –

    Policy instance

  • config

    (dict) –

    Parsed configuration

  • user_manager

    (UserManager) –

    An instance of the user manager.

Methods:

  • check_quota

    Sum all sessions since the last reset and check against the daily quota.

  • discover_agent_names_for_user

    Discover current org.guardian.Agent D-Bus names for the given user by listing names on the system bus.

  • get_active_users

    Return a list of currently active usernames.

  • get_agent_names_for_user

    Return the cached list of D-Bus agent names for a user, or empty list if not found.

  • get_agent_paths_for_user

    Returns a list of D-Bus object paths for agents belonging to the given user.

  • get_remaining_time

    Returns the remaining allowed time (in minutes) for the given user today.

  • get_total_time

    Returns the total allowed time (in minutes) for the given user today.

  • get_user_sessions

    Returns a list of active session details for the given user.

  • handle_login

    Register a new session on login for child accounts.

  • handle_logout

    End a session on logout and save it in the database for child accounts.

  • pause_user_time

    Pause time tracking for a user when a lock event is received for an unknown session.

  • perform_daily_reset

    Perform daily reset: delete sessions since last reset and reset quotas if needed.

  • periodic_session_update

    Periodically update all active sessions in the database with current duration.

  • receive_lock_event

    Called via D-Bus/IPC from agent to record lock/unlock events for a session.

  • refresh_agent_name_mapping

    Refresh the mapping of usernames to their current D-Bus agent names using discover_agent_names_for_user().

  • run

    Start session tracking, connect to systemd-logind via DBus, and listen for KDE lock events.

check_quota async

check_quota(username: str) -> bool

Sum all sessions since the last reset and check against the daily quota. Returns True if time remains, otherwise False.

Parameters:

  • username
    (str) –

    Username

Returns:

  • bool ( bool ) –

    True if time remains, False if limit reached

discover_agent_names_for_user async

discover_agent_names_for_user(username: str) -> list

Discover current org.guardian.Agent D-Bus names for the given user by listing names on the system bus. Returns a list of matching D-Bus names.

get_active_users async

get_active_users() -> list

Return a list of currently active usernames.

get_agent_names_for_user

get_agent_names_for_user(username: str) -> list

Return the cached list of D-Bus agent names for a user, or empty list if not found.

get_agent_paths_for_user

get_agent_paths_for_user(username: str)

Returns a list of D-Bus object paths for agents belonging to the given user. This should be tracked in active_sessions as 'agent_path' if available, otherwise default to /org/guardian/Agent or numbered agents.

get_remaining_time async

get_remaining_time(username: str) -> float

Returns the remaining allowed time (in minutes) for the given user today.

get_total_time async

get_total_time(username: str) -> float

Returns the total allowed time (in minutes) for the given user today.

get_user_sessions

get_user_sessions(username: str)

Returns a list of active session details for the given user. Each item is a dict with session_id, service, desktop, start_time, etc.

handle_login async

handle_login(session_id, uid, username, props)

Register a new session on login for child accounts. Skips systemd-user sessions. Also ensure user account is set up: PAM time rules, systemd user service, and agent.

Parameters:

  • session_id
    (str) –

    Session ID

  • uid
    (int) –

    User ID

  • username
    (str) –

    Username

handle_logout async

handle_logout(session_id)

End a session on logout and save it in the database for child accounts.

Parameters:

  • session_id
    (str) –

    Session ID

pause_user_time

pause_user_time(username, timestamp)

Pause time tracking for a user when a lock event is received for an unknown session.

perform_daily_reset

perform_daily_reset()

Perform daily reset: delete sessions since last reset and reset quotas if needed.

periodic_session_update async

periodic_session_update(interval: int = 60)

Periodically update all active sessions in the database with current duration.

receive_lock_event async

receive_lock_event(
    session_id: str,
    username: str,
    locked: bool,
    timestamp: float,
)

Called via D-Bus/IPC from agent to record lock/unlock events for a session. Also updates session progress in the database.

refresh_agent_name_mapping async

refresh_agent_name_mapping()

Refresh the mapping of usernames to their current D-Bus agent names using discover_agent_names_for_user(). Stores the mapping in self.agent_name_map: {username: [dbus_name, ...]}

run async

run()

Start session tracking, connect to systemd-logind via DBus, and listen for KDE lock events. Also checks for already logged-in child sessions on startup. Periodically updates session progress in the database.

storage

Central SQLite interface for guardian-daemon. Provides functions for session handling and future extensions.

Classes:

  • Storage

    Central SQLite interface for session and settings storage in Guardian Daemon.

Storage

Storage(db_path: str)

Central SQLite interface for session and settings storage in Guardian Daemon.

Parameters:

  • db_path

    (str) –

    Pfad zur SQLite-Datenbank.

Methods:

add_session

add_session(
    session_id: str,
    username: str,
    uid: int,
    start_time: float,
    end_time: float,
    duration: float,
    desktop: Optional[str] = None,
    service: Optional[str] = None,
)

Adds a new session to the database.

Parameters:

  • session_id
    (str) –

    Session ID

  • username
    (str) –

    Username

  • uid
    (int) –

    User ID

  • start_time
    (float) –

    Start time (EPOCH)

  • end_time
    (float) –

    End time (EPOCH)

  • duration
    (float) –

    Session duration

  • desktop
    (str, default: None ) –

    Desktop environment

  • service
    (str, default: None ) –

    Service (e.g. sddm)

close

close()

Close the database connection.

delete_sessions_since

delete_sessions_since(since: float)

Delete all sessions from the database since the given timestamp.

Parameters:

  • since
    (float) –

    Startzeitpunkt (Unix-Timestamp)

get_all_usernames

get_all_usernames() -> list

Return all usernames (except 'default') from the database.

Returns:

  • list ( list ) –

    List of usernames

get_last_reset_timestamp

get_last_reset_timestamp() -> Optional[float]

Retrieve the last daily reset timestamp from the database. Returns: float | None: EPOCH timestamp of last reset or None

get_sessions_for_user

get_sessions_for_user(
    username: str, since: Optional[float] = None
) -> list

Retrieve all sessions for a user, optionally since a specific time.

Parameters:

  • username
    (str) –

    Username

  • since
    (float, default: None ) –

    Start time (Unix timestamp)

Returns:

  • list ( list ) –

    List of sessions

get_user_settings

get_user_settings(username: str) -> Optional[dict]

Retrieve user settings from the database for the given username.

Parameters:

  • username
    (str) –

    Nutzername

Returns:

  • Optional[dict]

    dict | None: Einstellungen des Nutzers oder None

logind_to_epoch staticmethod

logind_to_epoch(logind_timestamp: int) -> float

Convert logind timestamp (microseconds since boot) to EPOCH timestamp.

Parameters:

  • logind_timestamp
    (int) –

    Microseconds since boot

Returns:

  • float ( float ) –

    EPOCH timestamp

set_last_reset_timestamp

set_last_reset_timestamp(ts: float)

Store the last daily reset timestamp in the database. Args: ts (float): EPOCH timestamp

set_user_settings

set_user_settings(username: str, settings: dict)

Store user settings in the database for the given username.

Parameters:

  • username
    (str) –

    Nutzername

  • settings
    (dict) –

    Einstellungen

sync_config_to_db

sync_config_to_db(config: dict)

Synchronize configuration data to the database.

Parameters:

  • config
    (dict) –

    Konfigurationsdaten

update_session_logout

update_session_logout(
    session_id: str, end_time: float, duration: float
)

Update session entry with logout time and duration.

update_session_progress

update_session_progress(session_id: str, duration: float)

Periodically update session entry with current duration (while session is active).

systemd_manager

Systemd manager for guardian-daemon. Creates and manages systemd timers/units for daily reset and curfew.

Classes:

  • SystemdManager

    Manages systemd timers and units for daily reset and curfew enforcement.

SystemdManager

SystemdManager()

Manages systemd timers and units for daily reset and curfew enforcement.

Methods:

create_curfew_timer

create_curfew_timer(start_time='22:00', end_time='06:00')

Create a systemd timer and service unit for curfew enforcement.

create_daily_reset_timer

create_daily_reset_timer(reset_time='03:00')

Create a systemd timer and corresponding service unit for the daily quota reset.

reload_systemd async

reload_systemd()

Reload systemd units to apply changes.

remove_timer_and_service

remove_timer_and_service(timer_name)

Remove a systemd timer and service unit by name.

user_manager

User manager for guardian-daemon. Manages login time windows for children via /etc/security/time.conf and handles user-specific systemd services.

Classes:

UserManager

UserManager(policy: Policy)

Methods:

  • ensure_kids_group

    Ensure the 'kids' group exists and all managed users are members of it.

  • ensure_pam_time_module

    Ensure that the pam_time.so module is properly configured in PAM services.

  • ensure_systemd_user_service

    Ensure that systemd user services are set up for the given user without enabling lingering.

  • remove_time_rules

    Remove time rules set by guardian-daemon from /etc/security/time.conf.

  • setup_dbus_policy

    Creates /etc/dbus-1/system.d/guardian.conf to allow group 'kids' access to org.guardian.Daemon.

  • setup_user_service

    Sets up the guardian_agent.service for the given user's systemd.

  • write_time_rules

    Updates the time rules for all children according to the policy in /etc/security/time.conf,

ensure_kids_group

ensure_kids_group()

Ensure the 'kids' group exists and all managed users are members of it.

ensure_pam_time_module

ensure_pam_time_module()

Ensure that the pam_time.so module is properly configured in PAM services.

ensure_systemd_user_service

ensure_systemd_user_service(username)

Ensure that systemd user services are set up for the given user without enabling lingering.

remove_time_rules

remove_time_rules()

Remove time rules set by guardian-daemon from /etc/security/time.conf.

setup_dbus_policy

setup_dbus_policy()

Creates /etc/dbus-1/system.d/guardian.conf to allow group 'kids' access to org.guardian.Daemon.

setup_user_service

setup_user_service(username: str)

Sets up the guardian_agent.service for the given user's systemd. Updates the service file if its checksum has changed.

write_time_rules

write_time_rules()

Updates the time rules for all children according to the policy in /etc/security/time.conf, without overwriting foreign rules.