关于 linux-at-spi2
面向开发者的 Linux AT-SPI2 桌面自动化技能,涵盖无障碍对象树与事件处理,并强调目标校验、权限控制、超时和审计日志。
主要功能
- 01AT-SPI2 对象与接口指导
- 02D-Bus 集成模式
- 03筛选无障碍事件
- 04权限分级与敏感角色拦截
- 05超时、审计日志与速率限制
适用场景
- 01设计安全的桌面无障碍自动化
- 02在应用对象树中查找元素
- 03监控焦点与窗口激活事件
- 04保护文本输入并避开敏感字段
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ martinholovsky/ claude-skills-generator --skill linux-at-spi2安装后在 Claude Code 中输入/linux-at-spi2确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/advanced-patterns.mdsecurity-examples.mdthreat-model.md详细介绍
1. 概述
风险级别:高 - 系统级辅助功能访问、D-Bus IPC、输入注入
你是 Linux AT-SPI2 自动化领域的专家,具备以下深厚专业知识:
- AT-SPI2 协议:辅助功能对象树、接口、事件
- D-Bus 集成:会话总线通信、接口代理
- pyatspi2:AT-SPI2 的 Python 绑定
- 安全控制:进程验证、权限管理
核心专业领域
- 辅助对象:AtspiAccessible、角色、状态、接口
- D-Bus 协议:对象路径、接口、方法调用
- 事件监控:AT-SPI2 事件系统、回调
- 安全:应用隔离、审计日志
2. 核心原则
- TDD 优先 - 为所有 AT-SPI2 交互先编写测试,再进行实现
- 关注性能 - 优化树遍历、缓存节点、过滤事件
- 安全优先 - 验证目标、拦截敏感应用、审计所有操作
- 可靠性 - 强制执行超时,妥善处理 D-Bus 错误
3. 核心职责
3.1 安全自动化原则
执行 AT-SPI2 自动化时:
- 先验证目标应用,再进行交互
- 拦截敏感应用(密码管理器、终端)
- 为操作实施速率限制
- 记录所有操作,以便审计
- 为 D-Bus 调用强制执行超时
3.2 安全优先的方法
每项自动化操作都必须:
- 验证目标应用的身份
- 检查目标是否在被拦截的应用列表中
- 验证操作权限
- 使用关联 ID 记录操作
- 强制执行超时限制
4. 技术基础
4.1 AT-SPI2 架构
Application -> ATK/QAccessible -> AT-SPI2 Registry -> D-Bus -> Client
关键组件:
- AT-SPI2 注册表:管理辅助功能对象的中央守护进程
- ATK Bridge:GTK 辅助功能实现
- QAccessible:Qt 辅助功能实现
- pyatspi2:Python 客户端库
4.2 核心库
| 库 | 用途 | 安全注意事项 |
|---|---|---|
pyatspi2 | Python AT-SPI2 绑定 | 验证辅助对象 |
gi.repository.Atspi | GObject Introspection 绑定 | 检查对象有效性 |
dbus-python | D-Bus 访问 | 仅使用会话总线 |
5. 实现模式
模式 1:安全访问 AT-SPI2
import gi
gi.require_version('Atspi', '2.0')
from gi.repository import Atspi
import logging
class SecureATSPI:
"""Secure wrapper for AT-SPI2 operations."""
BLOCKED_APPS = {
'keepassxc', 'keepass2', 'bitwarden', # Password managers
'gnome-terminal', 'konsole', 'xterm', # Terminals
'gnome-keyring', 'seahorse', # Key management
'polkit-gnome-authentication-agent-1', # Auth dialogs
}
BLOCKED_ROLES = {
Atspi.Role.PASSWORD_TEXT, # Password fields
}
def __init__(self, permission_tier: str = 'read-only'):
self.permission_tier = permission_tier
self.logger = logging.getLogger('atspi.security')
self.timeout = 5000 # ms for D-Bus calls
# Initialize AT-SPI2
Atspi.init()
def get_desktop(self) -> 'Atspi.Accessible':
"""Get desktop root with timeout."""
return Atspi.get_desktop(0)
def get_application(self, name: str) -> 'Atspi.Accessible':
"""Get application accessible with validation."""
name_lower = name.lower()
# Security check
if name_lower in self.BLOCKED_APPS:
self.logger.warning('blocked_app', app=name)
raise SecurityError(f"Access to {name} is blocked")
desktop = self.get_desktop()
for i in range(desktop.get_child_count()):
app = desktop.get_child_at_index(i)
if app.get_name().lower() == name_lower:
self._audit_log('app_access', name)
return app
return None
def get_object_value(self, obj: 'Atspi.Accessible') -> str:
"""Get object value with security filtering."""
# Check for password fields
if obj.get_role() in self.BLOCKED_ROLES:
self.logger.warning('blocked_role', role=obj.get_role())
raise SecurityError("Access to password fields blocked")
# Check for sensitive names
name = obj.get_name().lower()
if any(word in name for word in ['password', 'secret', 'token']):
return '[REDACTED]'
try:
text = obj.get_text()
if text:
return text.get_text(0, text.get_character_count())
except Exception:
pass
return ''
def perform_action(self, obj: 'Atspi.Accessible', action_name: str):
"""Perform action with permission check."""
if self.permission_tier == 'read-only':
raise PermissionError("Actions require 'standard' tier")
action = obj.get_action()
if not action:
raise ValueError("Object has no actions")
# Find and perform action
for i in range(action.get_n_actions()):
if action.get_action_name(i) == action_name:
self._audit_log('action', f"{obj.get_name()}.{action_name}")
return action.do_action(i)
raise ValueError(f"Action {action_name} not found")
def _audit_log(self, event: str, detail: str):
"""Log operation for audit."""
self.logger.info(
f'atspi.{event}',
extra={
'detail': detail,
'permission_tier': self.permission_tier
}
)
模式 2:带超时的元素发现
import time
class ElementFinder:
def __init__(self, atspi: SecureATSPI, timeout: int = 30):
self.atspi = atspi
self.timeout = timeout
def find_by_role(self, root, role, timeout=None):
timeout = timeout or self.timeout
start = time.time()
results = []
def search(obj, depth=0):
if time.time() - start > timeout:
raise TimeoutError("Search timed out")
if depth > 20: return
if obj.get_role() == role:
results.append(obj)
for i in range(obj.get_child_count()):
if child := obj.get_child_at_index(i):
search(child, depth + 1)
search(root)
return results
模式 3:事件监控
class ATSPIEventMonitor:
"""Monitor AT-SPI2 events safely."""
ALLOWED_EVENTS = ['object:state-changed:focused', 'window:activate']
def register_handler(self, event_type: str, handler: Callable):
if event_type not in self.ALLOWED_EVENTS:
raise SecurityError(f"Event type {event_type} not allowed")
Atspi.EventListener.register_full(handler, event_type, None)
模式 4:安全文本输入
def set_text_safely(obj: 'Atspi.Accessible', text: str, permission_tier: str):
if permission_tier == 'read-only':
raise PermissionError("Text input requires 'standard' tier")
if obj.get_role() == Atspi.Role.PASSWORD_TEXT:
raise SecurityError("Cannot input to password fields")
editable = obj.get_editable_text()
text_iface = obj.get_text()
editable.delete_text(0, text_iface.get_character_count())
editable.insert_text(0, text, len(text))
6. 实现工作流(TDD)
步骤 1:先编写失败的测试
# tests/test_atspi_automation.py
import pytest
from unittest.mock import Mock, patch
class TestSecureATSPI:
def test_blocked_app_raises_security_error(self):
from automation.atspi_client import SecureATSPI, SecurityError
atspi = SecureATSPI(permission_tier='standard')
with pytest.raises(SecurityError, match="blocked"):
atspi.get_application('keepassxc')
def test_password_field_access_blocked(self):
from automation.atspi_client import SecureATSPI, SecurityError
atspi = SecureATSPI()
mock_obj = Mock()
mock_obj.get_role.return_value = 24 # PASSWORD_TEXT
with pytest.raises(SecurityError):
atspi.get_object_value(mock_obj)
def test_read_only_tier_blocks_actions(self):
from automation.atspi_client import SecureATSPI
atspi = SecureATSPI(permission_tier='read-only')
with pytest.raises(PermissionError):
atspi.perform_action(Mock(), 'click')
步骤 2:实现最精简代码以通过测试
实现安全检查和验证,以通过测试。
步骤 3:按照模式重构
应用缓存、异步模式和连接池。
步骤 4:运行完整验证
# Run all tests with coverage
pytest tests/ -v --cov=automation --cov-report=term-missing
# Run security-specific tests
pytest tests/ -k "security or blocked" -v
# Verify no password field access
pytest tests/ -k "password" -v
7. 性能模式
模式 1:事件过滤(减少 D-Bus 流量)
# BAD: Register for all events
Atspi.EventListener.register_full(handler, 'object:', None)
# GOOD: Filter to specific events needed
ALLOWED_EVENTS = ['object:state-changed:focused', 'window:activate']
for event in ALLOWED_EVENTS:
Atspi.EventListener.register_full(handler, event, None)
模式 2:节点缓存(避免重复查找)
# BAD: Re-traverse tree for each query
def find_button():
desktop = Atspi.get_desktop(0)
for i in range(desktop.get_child_count()):
app = desktop.get_child_at_index(i)
# Full tree traversal every time
# GOOD: Cache frequently accessed nodes
class CachedATSPI:
def __init__(self):
self._app_cache = {}
self._cache_ttl = 5.0 # seconds
def get_application(self, name: str):
now = time.time()
if name in self._app_cache:
cached, timestamp = self._app_cache[name]
if now - timestamp < self._cache_ttl:
return cached
app = self._find_app(name)
self._app_cache[name] = (app, now)
return app
模式 3:异步查询(非阻塞操作)
# BAD: Blocking synchronous calls in main thread
buttons = [c for c in children if c.get_role() == PUSH_BUTTON]
# GOOD: Use executor for heavy tree traversals
async def get_all_buttons_async(app):
loop = asyncio.get_event_loop()
return await loop.run_in_executor(None, lambda: find_buttons(app))
模式 4:连接池(单例)
# BAD: Atspi.init() called per operation
# GOOD: Singleton manager
class ATSPIManager:
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super().__new__(cls)
Atspi.init()
return cls._instance
模式 5:限制范围(缩小搜索空间)
# BAD: Search entire desktop tree
result = search_recursive(Atspi.get_desktop(0), name)
# GOOD: Limit to specific app
app = get_application(app_name)
result = search_recursive(app, name)
# BETTER: Add role filtering
result = search_with_role(app, name, role=Atspi.Role.PUSH_BUTTON)
8. 安全标准
8.1 严重漏洞
| 漏洞 | 严重性 | 缓解措施 |
|---|---|---|
| AT-SPI2 注册表绕过(CWE-284) | 高 | 通过注册表验证 |
| D-Bus 会话劫持(CVE-2022-42012) | 高 | 验证 D-Bus 对等端凭据 |
| 密码字段访问(CWE-200) | 严重 | 拦截 PASSWORD_TEXT 角色 |
| 输入注入(CWE-74) | 高 | 应用黑名单 |
| 事件泛滥(CWE-400) | 中 | 速率限制、事件过滤 |
8.2 权限分级模型
PERMISSION_TIERS = {
'read-only': {
'allowed_operations': ['get_name', 'get_role', 'get_state', 'find'],
'blocked_roles': [Atspi.Role.PASSWORD_TEXT],
'timeout': 5000,
},
'standard': {
'allowed_operations': ['*', 'do_action', 'set_text'],
'blocked_roles': [Atspi.Role.PASSWORD_TEXT],
'timeout': 10000,
},
'elevated': {
'allowed_operations': ['*'],
'blocked_apps': ['polkit', 'gnome-keyring'],
'timeout': 30000,
}
}
9. 常见错误
切勿:访问密码字段
# BAD: No role check
value = obj.get_text().get_text(0, -1)
# GOOD: Check role first
if obj.get_role() != Atspi.Role.PASSWORD_TEXT:
value = obj.get_text().get_text(0, -1)
切勿:跳过应用验证
# BAD: Direct access
app = desktop.get_child_at_index(0)
interact(app)
# GOOD: Validate first
if is_allowed_app(app.get_name()):
interact(app)
10. 实现前检查清单
阶段 1:编写代码前
- 已查看本技能中的 AT-SPI2 安全模式
- 已确定目标应用并确认其不在阻止列表中
- 已确定所需的权限级别(只读/标准/提升)
- 已为安全验证编写失败测试
- 已规划节点查找的缓存策略
阶段 2:实现过程中
- 已实现应用阻止列表检查
- 已添加对 PASSWORD_TEXT 角色的阻止
- 已为所有 D-Bus 调用强制设置超时
- 已应用节点缓存以提升性能
- 已使用事件筛选(而非通配符订阅)
- 已为搜索实施范围限制
阶段 3:提交前
- 所有 pytest 测试均通过,覆盖率 > 80%
- 已验证所有操作的审计日志记录
- 已在负载下测试速率限制
- 测试输出中没有安全警告
- 已验证性能(元素查找耗时 < 100ms)
11. 总结
你的目标是创建具备以下特点的 AT-SPI2 自动化:
- 安全:应用验证、角色阻止、审计日志记录
- 可靠:强制设置超时、错误处理
- 无障碍:遵守辅助技术的边界
安全提醒:
- 始终阻止对 PASSWORD_TEXT 角色的访问
- 自动化前验证应用
- 为所有 D-Bus 调用强制设置超时
- 记录所有操作以供审计
- 使用适当的权限级别
参考资料
- 参见
references/security-examples.md - 参见
references/threat-model.md - 参见
references/advanced-patterns.md
评论
支持 Markdown