1. Overview Risk Level : HIGH - System service access, privileged operations, IPC You are an expert in D-Bus communication with deep expertise in: - D-Bus Protocol : Message bus system, object paths, interfaces - Bus Types : Session bus (user), System bus (privileged) - Service Interaction : Method calls, signals, properties - Security : Policy enforcement, peer credentials Core Expertise Areas 1. Bus Communication : Session/system bus, message routing 2. Object Model : Paths, interfaces, methods, signals 3. Policy Enforcement : D-Bus security policies, access control 4. Security Controls : C…

\n return bool(re.match(pattern, name)) and len(name) \u003c= 255\n\n def _audit_log(self, action: str, service: str, detail: str):\n \"\"\"Log operation for audit.\"\"\"\n self.logger.info(\n f'dbus.{action}',\n extra={\n 'service': service,\n 'detail': detail,\n 'permission_tier': self.permission_tier\n }\n )\n```\n\n### Pattern 2: Signal Monitoring\n\n```python\nfrom dbus.mainloop.glib import DBusGMainLoop\nfrom gi.repository import GLib\n\nclass SecureSignalMonitor:\n \"\"\"Monitor D-Bus signals safely.\"\"\"\n\n ALLOWED_SIGNALS = {\n 'org.freedesktop.Notifications': ['NotificationClosed', 'ActionInvoked'],\n 'org.freedesktop.FileManager1': ['OpenLocationRequested'],\n }\n\n def __init__(self, client: SecureDBusClient):\n self.client = client\n self.handlers = {}\n self.logger = logging.getLogger('dbus.signals')\n\n # Setup main loop\n DBusGMainLoop(set_as_default=True)\n\n def subscribe(\n self,\n bus_name: str,\n interface: str,\n signal: str,\n handler\n ):\n \"\"\"Subscribe to signal with validation.\"\"\"\n # Check if signal is allowed\n allowed = self.ALLOWED_SIGNALS.get(interface, [])\n if signal not in allowed:\n raise SecurityError(f\"Signal {interface}.{signal} not allowed\")\n\n # Wrapper to log signal receipt\n def safe_handler(*args):\n self.logger.info(\n 'signal_received',\n extra={'interface': interface, 'signal': signal}\n )\n handler(*args)\n\n # Subscribe\n self.client.bus.add_signal_receiver(\n safe_handler,\n signal_name=signal,\n dbus_interface=interface,\n bus_name=bus_name\n )\n self.handlers[(interface, signal)] = safe_handler\n\n def run(self, timeout: int = None):\n \"\"\"Run signal loop with timeout.\"\"\"\n loop = GLib.MainLoop()\n\n if timeout:\n GLib.timeout_add_seconds(timeout, loop.quit)\n\n loop.run()\n```\n\n### Pattern 3: Property Access Control\n\n```python\nclass SecurePropertyAccess:\n \"\"\"Controlled access to D-Bus properties.\"\"\"\n\n READABLE_PROPERTIES = {\n 'org.freedesktop.Notifications': ['ServerCapabilities'],\n 'org.mpris.MediaPlayer2': ['Identity', 'PlaybackStatus'],\n }\n\n WRITABLE_PROPERTIES = {\n 'org.mpris.MediaPlayer2.Player': ['Volume'],\n }\n\n def __init__(self, client: SecureDBusClient):\n self.client = client\n self.logger = logging.getLogger('dbus.properties')\n\n def get_property(\n self,\n bus_name: str,\n object_path: str,\n interface: str,\n property_name: str\n ):\n \"\"\"Get property with access control.\"\"\"\n # Check if property is readable\n allowed = self.READABLE_PROPERTIES.get(interface, [])\n if property_name not in allowed:\n raise SecurityError(f\"Property {interface}.{property_name} not readable\")\n\n proxy = self.client.get_object(bus_name, object_path)\n props = dbus.Interface(proxy, 'org.freedesktop.DBus.Properties')\n\n value = props.Get(interface, property_name)\n self.logger.info(\n 'property_read',\n extra={'interface': interface, 'property': property_name}\n )\n return value\n\n def set_property(\n self,\n bus_name: str,\n object_path: str,\n interface: str,\n property_name: str,\n value\n ):\n \"\"\"Set property with access control.\"\"\"\n if self.client.permission_tier == 'read-only':\n raise PermissionError(\"Setting properties requires 'standard' tier\")\n\n # Check if property is writable\n allowed = self.WRITABLE_PROPERTIES.get(interface, [])\n if property_name not in allowed:\n raise SecurityError(f\"Property {interface}.{property_name} not writable\")\n\n proxy = self.client.get_object(bus_name, object_path)\n props = dbus.Interface(proxy, 'org.freedesktop.DBus.Properties')\n\n props.Set(interface, property_name, value)\n self.logger.info(\n 'property_write',\n extra={'interface': interface, 'property': property_name}\n )\n```\n\n### Pattern 4: Service Discovery\n\n```python\nclass ServiceDiscovery:\n \"\"\"Discover D-Bus services safely.\"\"\"\n\n def __init__(self, client: SecureDBusClient):\n self.client = client\n\n def list_names(self) -> list:\n \"\"\"List available bus names (filtered).\"\"\"\n dbus_obj = self.client.bus.get_object(\n 'org.freedesktop.DBus',\n '/org/freedesktop/DBus'\n )\n dbus_iface = dbus.Interface(dbus_obj, 'org.freedesktop.DBus')\n\n all_names = dbus_iface.ListNames()\n\n # Filter blocked services\n filtered = [\n name for name in all_names\n if name not in SecureDBusClient.BLOCKED_SERVICES\n ]\n\n return filtered\n\n def introspect(self, bus_name: str, object_path: str) -> str:\n \"\"\"Get introspection XML for object.\"\"\"\n if bus_name in SecureDBusClient.BLOCKED_SERVICES:\n raise SecurityError(f\"Cannot introspect {bus_name}\")\n\n proxy = self.client.get_object(bus_name, object_path)\n return proxy.Introspect(\n dbus_interface='org.freedesktop.DBus.Introspectable'\n )\n```\n\n---\n\n## 5. Security Standards\n\n### 5.1 Critical Vulnerabilities\n\n#### 1. Privilege Escalation via PolicyKit (CVE-2021-4034)\n- **Severity**: CRITICAL\n- **Description**: Polkit vulnerability for local privilege escalation\n- **Mitigation**: Block PolicyKit service access\n\n#### 2. D-Bus Authentication Bypass (CVE-2022-42012)\n- **Severity**: HIGH\n- **Description**: Unauthorized session bus access\n- **Mitigation**: Validate peer credentials\n\n#### 3. Service Impersonation (CWE-290)\n- **Severity**: HIGH\n- **Description**: Malicious service claiming trusted name\n- **Mitigation**: Verify service credentials\n\n#### 4. Method Injection (CWE-74)\n- **Severity**: MEDIUM\n- **Description**: Malicious method parameters\n- **Mitigation**: Input validation, service allowlists\n\n#### 5. Information Disclosure (CWE-200)\n- **Severity**: MEDIUM\n- **Description**: Exposing sensitive service data\n- **Mitigation**: Property access control\n\n### 5.2 Permission Tier Model\n\n```python\nPERMISSION_TIERS = {\n 'read-only': {\n 'bus_type': 'session',\n 'allowed_operations': ['get_property', 'introspect', 'list_names'],\n 'blocked_services': BLOCKED_SERVICES,\n },\n 'standard': {\n 'bus_type': 'session',\n 'allowed_operations': ['*', 'set_property', 'call_method'],\n 'blocked_services': BLOCKED_SERVICES,\n },\n 'elevated': {\n 'bus_type': ['session', 'system'],\n 'allowed_operations': ['*'],\n 'blocked_services': ['org.freedesktop.PackageKit'],\n }\n}\n```\n\n---\n\n## 8. Common Mistakes\n\n### Never: Access System Bus Without Need\n\n```python\n# BAD: Always use system bus\nbus = dbus.SystemBus()\n\n# GOOD: Prefer session bus\nbus = dbus.SessionBus()\n# Only use system bus when required\n```\n\n### Never: Allow PolicyKit Access\n\n```python\n# BAD: No service filtering\nresult = client.call_method('org.freedesktop.PolicyKit1', ...)\n\n# GOOD: Block privileged services\nif service not in BLOCKED_SERVICES:\n result = client.call_method(service, ...)\n```\n\n### Never: Skip Timeout Enforcement\n\n```python\n# BAD: No timeout\nresult = iface.SomeMethod()\n\n# GOOD: With timeout\nresult = iface.SomeMethod(timeout=30)\n```\n\n---\n\n## 13. Pre-Deployment Checklist\n\n- [ ] Service blocklist configured\n- [ ] Session bus preferred over system bus\n- [ ] Timeout enforcement on all calls\n- [ ] Peer credential validation\n- [ ] Audit logging enabled\n- [ ] Property access control configured\n\n---\n\n## 14. Summary\n\nYour goal is to create D-Bus automation that is:\n- **Secure**: Service blocklists, credential validation, access control\n- **Reliable**: Timeout enforcement, error handling\n- **Minimal**: Session bus by default, least privilege\n\n**Security Reminders**:\n1. Always prefer session bus over system bus\n2. Block access to PolicyKit and systemd\n3. Validate peer credentials when needed\n4. Enforce timeouts on all method calls\n5. Log all operations for audit\n\n---\n\n## References\n\n- See `references/security-examples.md`\n- See `references/threat-model.md`\n- See `references/advanced-patterns.md`\n---","attachment_filenames":["references/advanced-patterns.md","references/security-examples.md","references/threat-model.md"],"attachments":[{"filename":"references/advanced-patterns.md","content":"# D-Bus - Advanced Patterns\n\n## Pattern: Async D-Bus with GIO\n\n```python\nfrom gi.repository import Gio, GLib\n\nclass AsyncDBusClient:\n \"\"\"Async D-Bus client using GIO.\"\"\"\n\n def __init__(self, bus_type: str = 'session'):\n if bus_type == 'session':\n self.bus = Gio.bus_get_sync(Gio.BusType.SESSION)\n else:\n self.bus = Gio.bus_get_sync(Gio.BusType.SYSTEM)\n\n def call_method_async(\n self,\n bus_name: str,\n object_path: str,\n interface: str,\n method: str,\n parameters: GLib.Variant,\n callback\n ):\n \"\"\"Call method asynchronously.\"\"\"\n self.bus.call(\n bus_name,\n object_path,\n interface,\n method,\n parameters,\n None,\n Gio.DBusCallFlags.NONE,\n 30000, # timeout ms\n None,\n callback\n )\n```\n\n## Pattern: Connection Pooling\n\n```python\nclass DBusConnectionPool:\n \"\"\"Pool D-Bus connections for reuse.\"\"\"\n\n def __init__(self, max_connections: int = 5):\n self.max_connections = max_connections\n self.connections = []\n self.lock = threading.Lock()\n\n def get_connection(self):\n \"\"\"Get connection from pool.\"\"\"\n with self.lock:\n if self.connections:\n return self.connections.pop()\n return dbus.SessionBus()\n\n def return_connection(self, conn):\n \"\"\"Return connection to pool.\"\"\"\n with self.lock:\n if len(self.connections) \u003c self.max_connections:\n self.connections.append(conn)\n```\n\n## Pattern: Service Wrapper\n\n```python\nclass NotificationService:\n \"\"\"Type-safe wrapper for Notifications service.\"\"\"\n\n BUS_NAME = 'org.freedesktop.Notifications'\n OBJECT_PATH = '/org/freedesktop/Notifications'\n INTERFACE = 'org.freedesktop.Notifications'\n\n def __init__(self, client: SecureDBusClient):\n self.client = client\n\n def notify(\n self,\n summary: str,\n body: str = '',\n icon: str = '',\n timeout: int = 5000\n ) -> int:\n \"\"\"Send notification.\"\"\"\n return self.client.call_method(\n self.BUS_NAME,\n self.OBJECT_PATH,\n self.INTERFACE,\n 'Notify',\n '', # app_name\n 0, # replaces_id\n icon,\n summary,\n body,\n [], # actions\n {}, # hints\n timeout\n )\n\n def close(self, notification_id: int):\n \"\"\"Close notification.\"\"\"\n return self.client.call_method(\n self.BUS_NAME,\n self.OBJECT_PATH,\n self.INTERFACE,\n 'CloseNotification',\n notification_id\n )\n```\n\n## Pattern: Retry Logic\n\n```python\nimport time\n\nclass RetryableDBusCall:\n \"\"\"Retry D-Bus calls on transient failures.\"\"\"\n\n RETRYABLE_ERRORS = [\n 'org.freedesktop.DBus.Error.ServiceUnknown',\n 'org.freedesktop.DBus.Error.NoReply',\n ]\n\n def __init__(self, max_retries: int = 3):\n self.max_retries = max_retries\n\n def call(self, method, *args, **kwargs):\n \"\"\"Call with retry on transient errors.\"\"\"\n for attempt in range(self.max_retries):\n try:\n return method(*args, **kwargs)\n except DBusException as e:\n if e.get_dbus_name() not in self.RETRYABLE_ERRORS:\n raise\n if attempt == self.max_retries - 1:\n raise\n time.sleep(2 ** attempt)\n```\n\n## Pattern: Interface Caching\n\n```python\nclass CachedInterfaceProxy:\n \"\"\"Cache D-Bus interface proxies.\"\"\"\n\n def __init__(self, client: SecureDBusClient):\n self.client = client\n self.cache = {}\n\n def get_interface(self, bus_name: str, object_path: str, interface: str):\n \"\"\"Get cached interface proxy.\"\"\"\n key = (bus_name, object_path, interface)\n\n if key not in self.cache:\n proxy = self.client.get_object(bus_name, object_path)\n self.cache[key] = dbus.Interface(proxy, interface)\n\n return self.cache[key]\n\n def invalidate(self, bus_name: str = None):\n \"\"\"Invalidate cache.\"\"\"\n if bus_name:\n keys = [k for k in self.cache if k[0] == bus_name]\n for key in keys:\n del self.cache[key]\n else:\n self.cache.clear()\n```\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":4458,"content_sha256":"cb331ec67c5b1b35838ed57ce257bc3ce4fee5113c2c08c51dee8bcecf1b4bae"},{"filename":"references/security-examples.md","content":"# D-Bus - Security Examples\n\n## Service Allowlist Pattern\n\n```python\nSERVICE_ALLOWLIST = {\n 'org.freedesktop.Notifications': ['Notify', 'CloseNotification'],\n 'org.mpris.MediaPlayer2': ['PlayPause', 'Stop', 'Next', 'Previous'],\n 'org.freedesktop.FileManager1': ['ShowItems', 'ShowFolders'],\n}\n\ndef validate_service_method(bus_name: str, method: str) -> bool:\n \"\"\"Validate service and method against allowlist.\"\"\"\n allowed_methods = SERVICE_ALLOWLIST.get(bus_name)\n if not allowed_methods:\n return False\n return method in allowed_methods\n```\n\n## Peer Credential Validation\n\n```python\ndef validate_peer_process(bus, bus_name: str, expected_exe: str) -> bool:\n \"\"\"Validate peer process credentials.\"\"\"\n dbus_obj = bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus')\n dbus_iface = dbus.Interface(dbus_obj, 'org.freedesktop.DBus')\n\n pid = dbus_iface.GetConnectionUnixProcessID(bus_name)\n\n # Read process executable\n try:\n exe = os.readlink(f'/proc/{pid}/exe')\n return exe == expected_exe\n except Exception:\n return False\n```\n\n## Input Validation\n\n```python\nimport re\n\ndef validate_object_path(path: str) -> bool:\n \"\"\"Validate D-Bus object path format.\"\"\"\n pattern = r'^(/[a-zA-Z0-9_]+)+

1. Overview Risk Level : HIGH - System service access, privileged operations, IPC You are an expert in D-Bus communication with deep expertise in: - D-Bus Protocol : Message bus system, object paths, interfaces - Bus Types : Session bus (user), System bus (privileged) - Service Interaction : Method calls, signals, properties - Security : Policy enforcement, peer credentials Core Expertise Areas 1. Bus Communication : Session/system bus, message routing 2. Object Model : Paths, interfaces, methods, signals 3. Policy Enforcement : D-Bus security policies, access control 4. Security Controls : C…

\n return bool(re.match(pattern, path)) and len(path) \u003c= 255\n\ndef validate_interface(interface: str) -> bool:\n \"\"\"Validate D-Bus interface format.\"\"\"\n pattern = r'^[a-zA-Z_][a-zA-Z0-9_]*(\\.[a-zA-Z_][a-zA-Z0-9_]*)+

1. Overview Risk Level : HIGH - System service access, privileged operations, IPC You are an expert in D-Bus communication with deep expertise in: - D-Bus Protocol : Message bus system, object paths, interfaces - Bus Types : Session bus (user), System bus (privileged) - Service Interaction : Method calls, signals, properties - Security : Policy enforcement, peer credentials Core Expertise Areas 1. Bus Communication : Session/system bus, message routing 2. Object Model : Paths, interfaces, methods, signals 3. Policy Enforcement : D-Bus security policies, access control 4. Security Controls : C…

\n return bool(re.match(pattern, interface)) and len(interface) \u003c= 255\n```\n\n## Audit Logging\n\n```python\nimport json\nimport logging\n\nclass DBusAuditLogger:\n \"\"\"D-Bus operation audit logging.\"\"\"\n\n def log_method_call(self, service: str, interface: str, method: str, success: bool):\n record = {\n 'timestamp': datetime.utcnow().isoformat(),\n 'event': 'dbus_method_call',\n 'service': service,\n 'interface': interface,\n 'method': method,\n 'success': success\n }\n logging.getLogger('dbus.audit').info(json.dumps(record))\n\n def log_blocked_access(self, service: str, reason: str):\n record = {\n 'timestamp': datetime.utcnow().isoformat(),\n 'event': 'dbus_blocked',\n 'service': service,\n 'reason': reason\n }\n logging.getLogger('dbus.audit').warning(json.dumps(record))\n```\n\n## Timeout Wrapper\n\n```python\nimport signal\n\ndef call_with_timeout(method, args, timeout: int = 30):\n \"\"\"Call D-Bus method with signal-based timeout.\"\"\"\n def handler(signum, frame):\n raise TimeoutError(f\"D-Bus call timed out after {timeout}s\")\n\n old = signal.signal(signal.SIGALRM, handler)\n signal.alarm(timeout)\n\n try:\n return method(*args)\n finally:\n signal.alarm(0)\n signal.signal(signal.SIGALRM, old)\n```\n\n## Error Handling\n\n```python\nfrom dbus.exceptions import DBusException\n\ndef safe_dbus_call(method, *args, **kwargs):\n \"\"\"Safely call D-Bus method with error handling.\"\"\"\n try:\n return method(*args, **kwargs)\n except DBusException as e:\n error_name = e.get_dbus_name()\n\n # Handle specific errors\n if 'ServiceUnknown' in error_name:\n raise ServiceNotFoundError(f\"Service not available\")\n elif 'AccessDenied' in error_name:\n raise PermissionError(f\"Access denied\")\n elif 'Timeout' in error_name:\n raise TimeoutError(f\"Operation timed out\")\n else:\n raise\n```\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3534,"content_sha256":"70726b53b4f4130dcb34225bb77aabd77e50444f6dcff88a385013e7c1b18982"},{"filename":"references/threat-model.md","content":"# D-Bus - Threat Model\n\n## Threat Model Overview\n\n**Domain Risk Level**: HIGH\n**Attack Surface**: System service access, IPC, privileged operations\n\n### Assets to Protect\n\n1. **System Services** - CRITICAL - PolicyKit, systemd\n2. **User Secrets** - CRITICAL - gnome-keyring\n3. **System Integrity** - HIGH - Package installation\n\n---\n\n## Attack Scenario 1: PolicyKit Privilege Escalation\n\n**Threat Level**: CRITICAL\n\n**Attack Flow**:\n```\n1. Call PolicyKit authentication methods\n2. Bypass or manipulate auth checks\n3. Gain root privileges\n4. Full system compromise\n```\n\n**Mitigation**: Block org.freedesktop.PolicyKit1 service\n\n---\n\n## Attack Scenario 2: Systemd Service Control\n\n**Threat Level**: CRITICAL\n\n**Attack Flow**:\n```\n1. Access systemd1 service\n2. Start/stop/modify system services\n3. Disable security services\n4. Compromise system\n```\n\n**Mitigation**: Block org.freedesktop.systemd1 service\n\n---\n\n## Attack Scenario 3: Secret Service Access\n\n**Threat Level**: CRITICAL\n\n**Attack Flow**:\n```\n1. Connect to secrets service\n2. Enumerate stored secrets\n3. Extract credentials\n4. Lateral movement\n```\n\n**Mitigation**: Block org.freedesktop.secrets service\n\n---\n\n## Attack Scenario 4: Package Installation\n\n**Threat Level**: HIGH\n\n**Attack Flow**:\n```\n1. Access PackageKit service\n2. Install malicious packages\n3. Achieve persistence\n```\n\n**Mitigation**: Block org.freedesktop.PackageKit service\n\n---\n\n## STRIDE Analysis\n\n| Category | Threats | Mitigations | Priority |\n|----------|---------|-------------|----------|\n| **Spoofing** | Service impersonation | Credential validation | HIGH |\n| **Tampering** | Method parameter manipulation | Input validation | MEDIUM |\n| **Repudiation** | Deny method calls | Audit logging | HIGH |\n| **Information Disclosure** | Read sensitive properties | Property access control | HIGH |\n| **Denial of Service** | Method flood | Rate limiting, timeouts | MEDIUM |\n| **Elevation of Privilege** | PolicyKit, systemd | Service blocklist | CRITICAL |\n\n---\n\n## Security Controls\n\n### Preventive\n- Service blocklists (PolicyKit, systemd, secrets)\n- Session bus preference\n- Method allowlists\n- Peer credential validation\n\n### Detective\n- Comprehensive audit logging\n- Service access monitoring\n- Anomaly detection\n\n### Corrective\n- Timeout enforcement\n- Automatic rate limiting\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":2312,"content_sha256":"be092680a30caab2ffa640849b0438a84a8f566d3b2eff1b894dbdd119ac3017"}],"content_json":{"type":"doc","content":[{"type":"heading","attrs":{"level":2},"content":[{"text":"1. Overview","type":"text"}]},{"type":"paragraph","content":[{"text":"Risk Level","type":"text","marks":[{"type":"strong"}]},{"text":": HIGH - System service access, privileged operations, IPC","type":"text"}]},{"type":"paragraph","content":[{"text":"You are an expert in D-Bus communication with deep expertise in:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"D-Bus Protocol","type":"text","marks":[{"type":"strong"}]},{"text":": Message bus system, object paths, interfaces","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Bus Types","type":"text","marks":[{"type":"strong"}]},{"text":": Session bus (user), System bus (privileged)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Service Interaction","type":"text","marks":[{"type":"strong"}]},{"text":": Method calls, signals, properties","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security","type":"text","marks":[{"type":"strong"}]},{"text":": Policy enforcement, peer credentials","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Core Expertise Areas","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Bus Communication","type":"text","marks":[{"type":"strong"}]},{"text":": Session/system bus, message routing","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Object Model","type":"text","marks":[{"type":"strong"}]},{"text":": Paths, interfaces, methods, signals","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Policy Enforcement","type":"text","marks":[{"type":"strong"}]},{"text":": D-Bus security policies, access control","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security Controls","type":"text","marks":[{"type":"strong"}]},{"text":": Credential validation, service allowlists","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"2. Core Principles","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"TDD First","type":"text","marks":[{"type":"strong"}]},{"text":" - Write tests before implementation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Performance Aware","type":"text","marks":[{"type":"strong"}]},{"text":" - Optimize connections, caching, async calls","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security First","type":"text","marks":[{"type":"strong"}]},{"text":" - Validate targets, block privileged services","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Minimal Privilege","type":"text","marks":[{"type":"strong"}]},{"text":" - Session bus by default, least access","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"3. Core Responsibilities","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"3.1 Safe IPC Principles","type":"text"}]},{"type":"paragraph","content":[{"text":"When using D-Bus:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Validate service targets","type":"text","marks":[{"type":"strong"}]},{"text":" before method calls","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use session bus","type":"text","marks":[{"type":"strong"}]},{"text":" unless system access required","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Block privileged services","type":"text","marks":[{"type":"strong"}]},{"text":" (PolicyKit, systemd)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Log all method invocations","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Enforce call timeouts","type":"text","marks":[{"type":"strong"}]}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"3.2 Security-First Approach","type":"text"}]},{"type":"paragraph","content":[{"text":"Every D-Bus operation MUST:","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Validate target service/interface","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Check against blocked service list","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use appropriate bus type","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Log operation details","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Enforce timeout limits","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"3.3 Bus Type Policy","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Session Bus","type":"text","marks":[{"type":"strong"}]},{"text":": User applications, non-privileged","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"System Bus","type":"text","marks":[{"type":"strong"}]},{"text":": System services, requires elevated permissions","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Default","type":"text","marks":[{"type":"strong"}]},{"text":": Always prefer session bus","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"4. Technical Foundation","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"4.1 D-Bus Architecture","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"Application -> D-Bus Library -> D-Bus Daemon -> Target Service","type":"text"}]},{"type":"paragraph","content":[{"text":"Key Concepts","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Bus Name","type":"text","marks":[{"type":"strong"}]},{"text":": Service identifier (e.g., ","type":"text"},{"text":"org.freedesktop.Notifications","type":"text","marks":[{"type":"code_inline"}]},{"text":")","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Object Path","type":"text","marks":[{"type":"strong"}]},{"text":": Object location (e.g., ","type":"text"},{"text":"/org/freedesktop/Notifications","type":"text","marks":[{"type":"code_inline"}]},{"text":")","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Interface","type":"text","marks":[{"type":"strong"}]},{"text":": Method grouping (e.g., ","type":"text"},{"text":"org.freedesktop.Notifications","type":"text","marks":[{"type":"code_inline"}]},{"text":")","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Member","type":"text","marks":[{"type":"strong"}]},{"text":": Method or signal name","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"4.2 Libraries","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Library","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Purpose","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Security Notes","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"dbus-python","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Python bindings","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Validate peer credentials","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"pydbus","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Modern Python D-Bus","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Use with service filtering","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"dasbus","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Async D-Bus","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Enforce timeouts","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"gi.repository.Gio","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"GIO D-Bus bindings","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Built-in security","type":"text"}]}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"5. Implementation Workflow (TDD)","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Step 1: Write Failing Test First","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"# tests/test_dbus_client.py\nimport pytest\nfrom unittest.mock import MagicMock, patch\n\nclass TestSecureDBusClient:\n \"\"\"Test D-Bus client with mocked bus.\"\"\"\n\n @pytest.fixture\n def mock_bus(self):\n with patch('dbus.SessionBus') as mock:\n yield mock.return_value\n\n def test_blocks_privileged_services(self, mock_bus):\n \"\"\"Should reject access to blocked services.\"\"\"\n from secure_dbus import SecureDBusClient\n\n client = SecureDBusClient()\n\n with pytest.raises(SecurityError) as exc:\n client.get_object('org.freedesktop.PolicyKit1', '/')\n\n assert 'blocked' in str(exc.value).lower()\n\n def test_validates_bus_name_format(self, mock_bus):\n \"\"\"Should reject malformed bus names.\"\"\"\n from secure_dbus import SecureDBusClient\n\n client = SecureDBusClient()\n\n with pytest.raises(ValueError):\n client.get_object('invalid..name', '/')\n\n def test_enforces_timeout(self, mock_bus):\n \"\"\"Should timeout long-running calls.\"\"\"\n from secure_dbus import SecureDBusClient\n\n client = SecureDBusClient()\n client.timeout = 1\n\n mock_bus.get_object.return_value.SomeMethod.side_effect = \\\n Exception('Timeout')\n\n with pytest.raises(TimeoutError):\n client.call_method(\n 'org.test.Service', '/', 'org.test.Interface', 'SomeMethod'\n )","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Step 2: Implement Minimum to Pass","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"# secure_dbus.py\nclass SecureDBusClient:\n BLOCKED_SERVICES = {'org.freedesktop.PolicyKit1'}\n\n def get_object(self, bus_name: str, object_path: str):\n if bus_name in self.BLOCKED_SERVICES:\n raise SecurityError(f\"Access to {bus_name} is blocked\")\n if not self._validate_bus_name(bus_name):\n raise ValueError(f\"Invalid bus name: {bus_name}\")\n return self.bus.get_object(bus_name, object_path)","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Step 3: Refactor Following Patterns","type":"text"}]},{"type":"paragraph","content":[{"text":"Add logging, credential validation, and property caching.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Step 4: Run Full Verification","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"# Run tests\npytest tests/test_dbus_client.py -v\n\n# Type checking\nmypy secure_dbus.py --strict\n\n# Coverage\npytest --cov=secure_dbus --cov-report=term-missing","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"6. Performance Patterns","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Pattern 1: Connection Reuse","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"# GOOD: Reuse connection\nclass DBusConnectionPool:\n _session_bus = None\n\n @classmethod\n def get_session_bus(cls):\n if cls._session_bus is None:\n cls._session_bus = dbus.SessionBus()\n return cls._session_bus\n\n# BAD: Create new connection each call\ndef get_service():\n bus = dbus.SessionBus() # Expensive!\n return bus.get_object('org.test.Service', '/')","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Pattern 2: Signal Filtering","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"# GOOD: Filter signals at subscription\nbus.add_signal_receiver(\n handler,\n signal_name='SpecificSignal', # Only this signal\n dbus_interface='org.test.Interface',\n path='/specific/path' # Only this path\n)\n\n# BAD: Receive all signals and filter in handler\nbus.add_signal_receiver(\n handler,\n signal_name=None, # All signals - expensive!\n dbus_interface=None\n)","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Pattern 3: Async Calls with dasbus","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"# GOOD: Async calls for non-blocking operations\nfrom dasbus.connection import SessionMessageBus\nfrom dasbus.loop import EventLoop\nimport asyncio\n\nasync def async_call():\n bus = SessionMessageBus()\n proxy = bus.get_proxy('org.test.Service', '/')\n result = await asyncio.to_thread(proxy.Method)\n return result\n\n# BAD: Blocking calls in async context\ndef blocking_call():\n bus = dbus.SessionBus()\n proxy = bus.get_object('org.test.Service', '/')\n return proxy.Method() # Blocks event loop!","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Pattern 4: Message Batching","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"# GOOD: Batch property reads\ndef get_all_properties(proxy, interface):\n props = dbus.Interface(proxy, 'org.freedesktop.DBus.Properties')\n return props.GetAll(interface) # One call\n\n# BAD: Individual property reads\ndef get_properties_slow(proxy, interface):\n props = dbus.Interface(proxy, 'org.freedesktop.DBus.Properties')\n return {\n 'prop1': props.Get(interface, 'prop1'), # Call 1\n 'prop2': props.Get(interface, 'prop2'), # Call 2\n 'prop3': props.Get(interface, 'prop3'), # Call 3\n }","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Pattern 5: Property Caching","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"# GOOD: Cache properties with TTL\nfrom functools import lru_cache\nfrom time import time\n\nclass CachedPropertyAccess:\n def __init__(self, client, cache_ttl=5):\n self.client = client\n self.cache_ttl = cache_ttl\n self._cache = {}\n\n def get_property(self, bus_name, path, interface, prop):\n key = (bus_name, path, interface, prop)\n cached = self._cache.get(key)\n\n if cached and time() - cached['time'] \u003c self.cache_ttl:\n return cached['value']\n\n value = self._fetch_property(bus_name, path, interface, prop)\n self._cache[key] = {'value': value, 'time': time()}\n return value\n\n# BAD: Fetch property every time\ndef get_property(proxy, interface, prop):\n props = dbus.Interface(proxy, 'org.freedesktop.DBus.Properties')\n return props.Get(interface, prop) # Always fetches","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"7. Implementation Patterns","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Pattern 1: Secure D-Bus Client","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"import dbus\nfrom dbus.exceptions import DBusException\nimport logging\n\nclass SecureDBusClient:\n \"\"\"Secure D-Bus client with access controls.\"\"\"\n\n BLOCKED_SERVICES = {\n 'org.freedesktop.PolicyKit1', # Privilege escalation\n 'org.freedesktop.systemd1', # System service control\n 'org.freedesktop.login1', # Session/power management\n 'org.gnome.keyring', # Secret storage\n 'org.freedesktop.secrets', # Secret service\n 'org.freedesktop.PackageKit', # Package installation\n }\n\n BLOCKED_INTERFACES = {\n 'org.freedesktop.DBus.Properties', # Can read/write any property\n }\n\n def __init__(self, bus_type: str = 'session', permission_tier: str = 'standard'):\n self.permission_tier = permission_tier\n self.logger = logging.getLogger('dbus.security')\n self.timeout = 30 # seconds\n\n # Connect to bus\n if bus_type == 'session':\n self.bus = dbus.SessionBus()\n elif bus_type == 'system':\n if permission_tier != 'elevated':\n raise PermissionError(\"System bus requires 'elevated' tier\")\n self.bus = dbus.SystemBus()\n else:\n raise ValueError(f\"Invalid bus type: {bus_type}\")\n\n def get_object(self, bus_name: str, object_path: str) -> dbus.Interface:\n \"\"\"Get D-Bus object with validation.\"\"\"\n # Security check\n if bus_name in self.BLOCKED_SERVICES:\n self.logger.warning('blocked_service', service=bus_name)\n raise SecurityError(f\"Access to {bus_name} is blocked\")\n\n # Validate bus name format\n if not self._validate_bus_name(bus_name):\n raise ValueError(f\"Invalid bus name: {bus_name}\")\n\n # Get proxy object\n try:\n proxy = self.bus.get_object(bus_name, object_path)\n self._audit_log('get_object', bus_name, object_path)\n return proxy\n except DBusException as e:\n self.logger.error(f\"D-Bus error: {e}\")\n raise\n\n def call_method(\n self,\n bus_name: str,\n object_path: str,\n interface: str,\n method: str,\n *args\n ):\n \"\"\"Call D-Bus method with validation.\"\"\"\n # Security checks\n if interface in self.BLOCKED_INTERFACES:\n raise SecurityError(f\"Interface {interface} is blocked\")\n\n # Get object\n proxy = self.get_object(bus_name, object_path)\n iface = dbus.Interface(proxy, interface)\n\n # Call with timeout\n try:\n result = getattr(iface, method)(\n *args,\n timeout=self.timeout\n )\n self._audit_log('call_method', bus_name, f\"{interface}.{method}\")\n return result\n except DBusException as e:\n if 'Timeout' in str(e):\n raise TimeoutError(f\"Method call timed out after {self.timeout}s\")\n raise\n\n def get_peer_credentials(self, bus_name: str) -> dict:\n \"\"\"Get credentials of D-Bus peer.\"\"\"\n dbus_obj = self.bus.get_object(\n 'org.freedesktop.DBus',\n '/org/freedesktop/DBus'\n )\n dbus_iface = dbus.Interface(dbus_obj, 'org.freedesktop.DBus')\n\n return {\n 'pid': dbus_iface.GetConnectionUnixProcessID(bus_name),\n 'uid': dbus_iface.GetConnectionUnixUser(bus_name),\n }\n\n def _validate_bus_name(self, name: str) -> bool:\n \"\"\"Validate D-Bus bus name format.\"\"\"\n import re\n pattern = r'^[a-zA-Z_][a-zA-Z0-9_]*(\\.[a-zA-Z_][a-zA-Z0-9_]*)+

1. Overview Risk Level : HIGH - System service access, privileged operations, IPC You are an expert in D-Bus communication with deep expertise in: - D-Bus Protocol : Message bus system, object paths, interfaces - Bus Types : Session bus (user), System bus (privileged) - Service Interaction : Method calls, signals, properties - Security : Policy enforcement, peer credentials Core Expertise Areas 1. Bus Communication : Session/system bus, message routing 2. Object Model : Paths, interfaces, methods, signals 3. Policy Enforcement : D-Bus security policies, access control 4. Security Controls : C…

\n return bool(re.match(pattern, name)) and len(name) \u003c= 255\n\n def _audit_log(self, action: str, service: str, detail: str):\n \"\"\"Log operation for audit.\"\"\"\n self.logger.info(\n f'dbus.{action}',\n extra={\n 'service': service,\n 'detail': detail,\n 'permission_tier': self.permission_tier\n }\n )","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Pattern 2: Signal Monitoring","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"from dbus.mainloop.glib import DBusGMainLoop\nfrom gi.repository import GLib\n\nclass SecureSignalMonitor:\n \"\"\"Monitor D-Bus signals safely.\"\"\"\n\n ALLOWED_SIGNALS = {\n 'org.freedesktop.Notifications': ['NotificationClosed', 'ActionInvoked'],\n 'org.freedesktop.FileManager1': ['OpenLocationRequested'],\n }\n\n def __init__(self, client: SecureDBusClient):\n self.client = client\n self.handlers = {}\n self.logger = logging.getLogger('dbus.signals')\n\n # Setup main loop\n DBusGMainLoop(set_as_default=True)\n\n def subscribe(\n self,\n bus_name: str,\n interface: str,\n signal: str,\n handler\n ):\n \"\"\"Subscribe to signal with validation.\"\"\"\n # Check if signal is allowed\n allowed = self.ALLOWED_SIGNALS.get(interface, [])\n if signal not in allowed:\n raise SecurityError(f\"Signal {interface}.{signal} not allowed\")\n\n # Wrapper to log signal receipt\n def safe_handler(*args):\n self.logger.info(\n 'signal_received',\n extra={'interface': interface, 'signal': signal}\n )\n handler(*args)\n\n # Subscribe\n self.client.bus.add_signal_receiver(\n safe_handler,\n signal_name=signal,\n dbus_interface=interface,\n bus_name=bus_name\n )\n self.handlers[(interface, signal)] = safe_handler\n\n def run(self, timeout: int = None):\n \"\"\"Run signal loop with timeout.\"\"\"\n loop = GLib.MainLoop()\n\n if timeout:\n GLib.timeout_add_seconds(timeout, loop.quit)\n\n loop.run()","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Pattern 3: Property Access Control","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"class SecurePropertyAccess:\n \"\"\"Controlled access to D-Bus properties.\"\"\"\n\n READABLE_PROPERTIES = {\n 'org.freedesktop.Notifications': ['ServerCapabilities'],\n 'org.mpris.MediaPlayer2': ['Identity', 'PlaybackStatus'],\n }\n\n WRITABLE_PROPERTIES = {\n 'org.mpris.MediaPlayer2.Player': ['Volume'],\n }\n\n def __init__(self, client: SecureDBusClient):\n self.client = client\n self.logger = logging.getLogger('dbus.properties')\n\n def get_property(\n self,\n bus_name: str,\n object_path: str,\n interface: str,\n property_name: str\n ):\n \"\"\"Get property with access control.\"\"\"\n # Check if property is readable\n allowed = self.READABLE_PROPERTIES.get(interface, [])\n if property_name not in allowed:\n raise SecurityError(f\"Property {interface}.{property_name} not readable\")\n\n proxy = self.client.get_object(bus_name, object_path)\n props = dbus.Interface(proxy, 'org.freedesktop.DBus.Properties')\n\n value = props.Get(interface, property_name)\n self.logger.info(\n 'property_read',\n extra={'interface': interface, 'property': property_name}\n )\n return value\n\n def set_property(\n self,\n bus_name: str,\n object_path: str,\n interface: str,\n property_name: str,\n value\n ):\n \"\"\"Set property with access control.\"\"\"\n if self.client.permission_tier == 'read-only':\n raise PermissionError(\"Setting properties requires 'standard' tier\")\n\n # Check if property is writable\n allowed = self.WRITABLE_PROPERTIES.get(interface, [])\n if property_name not in allowed:\n raise SecurityError(f\"Property {interface}.{property_name} not writable\")\n\n proxy = self.client.get_object(bus_name, object_path)\n props = dbus.Interface(proxy, 'org.freedesktop.DBus.Properties')\n\n props.Set(interface, property_name, value)\n self.logger.info(\n 'property_write',\n extra={'interface': interface, 'property': property_name}\n )","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Pattern 4: Service Discovery","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"class ServiceDiscovery:\n \"\"\"Discover D-Bus services safely.\"\"\"\n\n def __init__(self, client: SecureDBusClient):\n self.client = client\n\n def list_names(self) -> list:\n \"\"\"List available bus names (filtered).\"\"\"\n dbus_obj = self.client.bus.get_object(\n 'org.freedesktop.DBus',\n '/org/freedesktop/DBus'\n )\n dbus_iface = dbus.Interface(dbus_obj, 'org.freedesktop.DBus')\n\n all_names = dbus_iface.ListNames()\n\n # Filter blocked services\n filtered = [\n name for name in all_names\n if name not in SecureDBusClient.BLOCKED_SERVICES\n ]\n\n return filtered\n\n def introspect(self, bus_name: str, object_path: str) -> str:\n \"\"\"Get introspection XML for object.\"\"\"\n if bus_name in SecureDBusClient.BLOCKED_SERVICES:\n raise SecurityError(f\"Cannot introspect {bus_name}\")\n\n proxy = self.client.get_object(bus_name, object_path)\n return proxy.Introspect(\n dbus_interface='org.freedesktop.DBus.Introspectable'\n )","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"5. Security Standards","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"5.1 Critical Vulnerabilities","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"1. Privilege Escalation via PolicyKit (CVE-2021-4034)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Severity","type":"text","marks":[{"type":"strong"}]},{"text":": CRITICAL","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Description","type":"text","marks":[{"type":"strong"}]},{"text":": Polkit vulnerability for local privilege escalation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Mitigation","type":"text","marks":[{"type":"strong"}]},{"text":": Block PolicyKit service access","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"2. D-Bus Authentication Bypass (CVE-2022-42012)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Severity","type":"text","marks":[{"type":"strong"}]},{"text":": HIGH","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Description","type":"text","marks":[{"type":"strong"}]},{"text":": Unauthorized session bus access","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Mitigation","type":"text","marks":[{"type":"strong"}]},{"text":": Validate peer credentials","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"3. Service Impersonation (CWE-290)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Severity","type":"text","marks":[{"type":"strong"}]},{"text":": HIGH","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Description","type":"text","marks":[{"type":"strong"}]},{"text":": Malicious service claiming trusted name","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Mitigation","type":"text","marks":[{"type":"strong"}]},{"text":": Verify service credentials","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"4. Method Injection (CWE-74)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Severity","type":"text","marks":[{"type":"strong"}]},{"text":": MEDIUM","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Description","type":"text","marks":[{"type":"strong"}]},{"text":": Malicious method parameters","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Mitigation","type":"text","marks":[{"type":"strong"}]},{"text":": Input validation, service allowlists","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"5. Information Disclosure (CWE-200)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Severity","type":"text","marks":[{"type":"strong"}]},{"text":": MEDIUM","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Description","type":"text","marks":[{"type":"strong"}]},{"text":": Exposing sensitive service data","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Mitigation","type":"text","marks":[{"type":"strong"}]},{"text":": Property access control","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"5.2 Permission Tier Model","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"PERMISSION_TIERS = {\n 'read-only': {\n 'bus_type': 'session',\n 'allowed_operations': ['get_property', 'introspect', 'list_names'],\n 'blocked_services': BLOCKED_SERVICES,\n },\n 'standard': {\n 'bus_type': 'session',\n 'allowed_operations': ['*', 'set_property', 'call_method'],\n 'blocked_services': BLOCKED_SERVICES,\n },\n 'elevated': {\n 'bus_type': ['session', 'system'],\n 'allowed_operations': ['*'],\n 'blocked_services': ['org.freedesktop.PackageKit'],\n }\n}","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"8. Common Mistakes","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Never: Access System Bus Without Need","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"# BAD: Always use system bus\nbus = dbus.SystemBus()\n\n# GOOD: Prefer session bus\nbus = dbus.SessionBus()\n# Only use system bus when required","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Never: Allow PolicyKit Access","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"# BAD: No service filtering\nresult = client.call_method('org.freedesktop.PolicyKit1', ...)\n\n# GOOD: Block privileged services\nif service not in BLOCKED_SERVICES:\n result = client.call_method(service, ...)","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Never: Skip Timeout Enforcement","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"# BAD: No timeout\nresult = iface.SomeMethod()\n\n# GOOD: With timeout\nresult = iface.SomeMethod(timeout=30)","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"13. Pre-Deployment Checklist","type":"text"}]},{"type":"checkbox_list","attrs":{"id":null},"content":[{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Service blocklist configured","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Session bus preferred over system bus","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Timeout enforcement on all calls","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Peer credential validation","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Audit logging enabled","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Property access control configured","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"14. Summary","type":"text"}]},{"type":"paragraph","content":[{"text":"Your goal is to create D-Bus automation that is:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Secure","type":"text","marks":[{"type":"strong"}]},{"text":": Service blocklists, credential validation, access control","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Reliable","type":"text","marks":[{"type":"strong"}]},{"text":": Timeout enforcement, error handling","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Minimal","type":"text","marks":[{"type":"strong"}]},{"text":": Session bus by default, least privilege","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Security Reminders","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Always prefer session bus over system bus","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Block access to PolicyKit and systemd","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Validate peer credentials when needed","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Enforce timeouts on all method calls","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Log all operations for audit","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"References","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"See ","type":"text"},{"text":"references/security-examples.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"See ","type":"text"},{"text":"references/threat-model.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"See ","type":"text"},{"text":"references/advanced-patterns.md","type":"text","marks":[{"type":"code_inline"}]}]}]}]},{"type":"hr","attrs":{"markup":"---"}}]},"metadata":{"date":"2026-06-05","name":"dbus","model":"sonnet","author":"@skillopedia","source":{"stars":38,"repo_name":"claude-skills-generator","origin_url":"https://github.com/martinholovsky/claude-skills-generator/blob/HEAD/skills/dbus/SKILL.md","repo_owner":"martinholovsky","body_sha256":"d68e1829ba87d0c61bbb0948ef7b99f21c4368eb59a0e5c43ed30450af413ffd","cluster_key":"1b4093ee042d2b243e586b0fa7bbe136009371a0b619b82da680a1fec73ed77e","clean_bundle":{"format":"clean-skill-bundle-v1","source":"martinholovsky/claude-skills-generator/skills/dbus/SKILL.md","attachments":[{"id":"36aeb495-11c3-54bc-a0af-e56440db43e3","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/36aeb495-11c3-54bc-a0af-e56440db43e3/attachment.md","path":"references/advanced-patterns.md","size":4458,"sha256":"cb331ec67c5b1b35838ed57ce257bc3ce4fee5113c2c08c51dee8bcecf1b4bae","contentType":"text/markdown; charset=utf-8"},{"id":"d8d04253-386e-5d6c-92fe-66da55a78c01","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/d8d04253-386e-5d6c-92fe-66da55a78c01/attachment.md","path":"references/security-examples.md","size":3534,"sha256":"70726b53b4f4130dcb34225bb77aabd77e50444f6dcff88a385013e7c1b18982","contentType":"text/markdown; charset=utf-8"},{"id":"e5df51ed-9c39-5622-8c4e-4c931ebe06e7","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/e5df51ed-9c39-5622-8c4e-4c931ebe06e7/attachment.md","path":"references/threat-model.md","size":2312,"sha256":"be092680a30caab2ffa640849b0438a84a8f566d3b2eff1b894dbdd119ac3017","contentType":"text/markdown; charset=utf-8"}],"bundle_sha256":"5bcb7a863de53f606fc1ce9b0ab4b92d9692f4def89a346891a57fefc79ae9a7","attachment_count":3,"text_attachments":3,"attachment_storage":"skillopedia-attachments-v1","binary_attachments":0,"excluded_attachments":[]},"cluster_size":1,"skill_md_path":"skills/dbus/SKILL.md","import_metadata":{"date":"2026-06-05","author":"@skillopedia","version":"v1","category":"design-ux","category_label":"Design"},"exact_dupes_collapsed_into_this":0},"version":"v1","category":"design-ux","import_tag":"clean-skills-v1","risk_level":"MEDIUM","description":"Expert in D-Bus IPC (Inter-Process Communication) on Linux systems. Specializes in secure service communication, method calls, signal handling, and system integration. HIGH-RISK skill due to system service access and privileged operations."}},"renderedAt":1782986763942}

1. Overview Risk Level : HIGH - System service access, privileged operations, IPC You are an expert in D-Bus communication with deep expertise in: - D-Bus Protocol : Message bus system, object paths, interfaces - Bus Types : Session bus (user), System bus (privileged) - Service Interaction : Method calls, signals, properties - Security : Policy enforcement, peer credentials Core Expertise Areas 1. Bus Communication : Session/system bus, message routing 2. Object Model : Paths, interfaces, methods, signals 3. Policy Enforcement : D-Bus security policies, access control 4. Security Controls : C…