feat(v1.2): 规则脚本沙箱(builtins 白名单)+ 探针,边界如实写明
你选了"限制 import(builtins 白名单)"。实现 `kernel/rule_sandbox.py`。 ## 三层防线 1. **静态扫描**:源码里出现 `__双下划线__` / `import` / `open|eval|exec|getattr|globals|...` 直接拒绝 (带行号 + 人话理由,界面上直接显示给用户) 2. **受限 builtins**:`exec` 时只喂白名单(算数 / 字符串 / 列表字典 / 异常), `__import__` 不在里面 → 没有模块系统 3. **硬超时**:复用 `timeouts.py` ## ★ 诚实性:探针专门测**它挡不住的地方** 一个只测"能挡住"的探针会让人误以为这是真沙箱,进而在导入警告里写 "安全沙箱,请放心导入"。所以第 6 节测的全是漏洞: - 第一层是**文本扫描**不是语义分析:`D = "_" * 2` 拼出来的双下划线能过 → 只要不把 `__` 直接写进源码,第一层就形同虚设 - **没有资源限制**:死循环只能靠超时兜底、`[0] * 10**9` 能吃掉几百 MB - 因此 `IMPORT_WARNING` 里**不能**出现"安全沙箱"(探针里也钉了这条断言) 警告文案因此写成实话:"这不是真正的沙箱,精心构造的脚本仍然可能读到 设备上的文件,也可能拖慢手机,只导入你信得过的来源。" ## 为什么最后没上子进程 翻回 `docs/v1.2实施计划.md` 那一节:安卓内核是 Chaquopy 嵌的 CPython, **没有独立解释器可执行文件**(证据:`python_run` 用进程内 `exec`, 注释写着"这就是本工具存在的意义")。要起真子进程只能用 Termux 的 `python3` + 常驻 worker + IPC 协议 —— 为一个"改个数值"不值得。 接口留好了:`run()` 的签名就是边界,以后要换实现不用改调用方。 ## 验证 `scripts/probe-rule-sandbox.py` 6 节 50+ 项全绿: 正常脚本能跑 / 13 种攻击全部拒绝 / 拒绝理由带行号且是人话 / 白名单里确实没有危险函数 / 受限命名空间里真的拿不到 / **挡不住的也测了**。
This commit is contained in:
145
scripts/probe-rule-sandbox.py
Normal file
145
scripts/probe-rule-sandbox.py
Normal file
@@ -0,0 +1,145 @@
|
||||
"""规则脚本沙箱的探针(v1.2 附录 E)。
|
||||
|
||||
**这个探针的重点是"逃逸尝试"** —— 沙箱的价值不在于"正常脚本能跑",
|
||||
而在于"不该跑的跑不起来"。所以这里一半的断言是攻击。
|
||||
|
||||
★ 同时也要钉住**它挡不住什么**:文档里说了"挡手滑不挡有意",
|
||||
那就得有个测试**证明这句话是对的**(构造一个能绕过去的脚本)。
|
||||
一个只测"能挡住"的探针会让人误以为它是真沙箱。
|
||||
|
||||
用法:`python scripts/probe-rule-sandbox.py`
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
REPO = os.path.abspath(os.path.join(HERE, ".."))
|
||||
os.environ["DOUBAO_DATA"] = tempfile.mkdtemp(prefix="doubao-sandbox-")
|
||||
sys.path.insert(0, os.path.join(REPO, "android", "kernel"))
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
if cond:
|
||||
print(f" ✓ {label}")
|
||||
else:
|
||||
fails.append(label)
|
||||
print(f" ✗ {label} {detail}")
|
||||
|
||||
|
||||
import rule_sandbox as S # noqa: E402
|
||||
|
||||
|
||||
def rejected(src):
|
||||
"""跑一下,返回拒绝原因(空串 = 没被拒绝)"""
|
||||
try:
|
||||
S.load(src, '<probe>', {})
|
||||
return ''
|
||||
except S.ScriptRejected as exc:
|
||||
return str(exc)
|
||||
|
||||
|
||||
def main():
|
||||
print("\n=== 1. 正常的规则脚本要能跑 ===")
|
||||
good = '''
|
||||
def on_stat_change(name, value, delta):
|
||||
# 好感度:正向变化翻倍(客气话效果更好)
|
||||
if delta > 0:
|
||||
delta = delta * 2
|
||||
return delta
|
||||
'''
|
||||
check("正常脚本通过扫描", rejected(good) == '', rejected(good))
|
||||
ns = S.load(good, '<probe>', {})
|
||||
check("能调到入口函数", S.call(ns, 'on_stat_change', '好感度', 10, 5) == 10)
|
||||
check("函数没定义时报 KeyError(调用方转成能看懂的话)",
|
||||
(lambda: [S.call(ns, 'on_turn') and False or True][0] if False else
|
||||
_raises_keyerror(ns)), "")
|
||||
|
||||
print("\n=== 2. 该拒绝的必须拒绝(手滑 + 抄来的脚本)===")
|
||||
attacks = [
|
||||
("import 模块", "import os\n\ndef on_turn(a, b):\n return os.getcwd()\n"),
|
||||
("from 引入", "from os import path\n\ndef on_turn(a, b):\n return 1\n"),
|
||||
("直接 open", "def on_turn(a, b):\n return open('/etc/passwd').read()\n"),
|
||||
("eval", "def on_turn(a, b):\n return eval('1+1')\n"),
|
||||
("exec", "def on_turn(a, b):\n exec('x=1')\n return x\n"),
|
||||
("compile", "def on_turn(a, b):\n return compile('1', '<x>', 'eval')\n"),
|
||||
("__import__", "def on_turn(a, b):\n return __import__('os').getcwd()\n"),
|
||||
("getattr 链", "def on_turn(a, b):\n return getattr(a, '__class__')\n"),
|
||||
("globals", "def on_turn(a, b):\n return globals()\n"),
|
||||
("__class__ 逃逸", "def on_turn(a, b):\n return ().__class__.__bases__[0]\n"),
|
||||
("__subclasses__ 逃逸", "def on_turn(a, b):\n return ().__class__.__bases__[0].__subclasses__()\n"),
|
||||
("__globals__ 偷函数", "def on_turn(a, b):\n return (lambda: 0).__globals__\n"),
|
||||
("quit()", "def on_turn(a, b):\n quit()\n"),
|
||||
]
|
||||
for label, src in attacks:
|
||||
why = rejected(src)
|
||||
check(f"{label} → 拒绝", why != '', "居然通过了!")
|
||||
|
||||
print("\n=== 3. 拒绝理由要人话(写在界面上给用户看)===")
|
||||
why = rejected("import os\n")
|
||||
check("提到行号", "第 1 行" in why, why)
|
||||
check("不光是术语(有解释)", len(why) > 12, why)
|
||||
print(f" 实际文案:{why}")
|
||||
|
||||
print("\n=== 4. 白名单里确实没有危险函数 ===")
|
||||
for bad in ('__import__', 'open', 'eval', 'exec', 'compile',
|
||||
'getattr', 'setattr', 'globals', 'locals', 'vars', 'dir',
|
||||
'type', 'object', 'super', 'input'):
|
||||
check(f"SAFE_BUILTINS 里没有 {bad}", bad not in S.SAFE_BUILTINS)
|
||||
|
||||
print("\n=== 5. 但受限命名空间里真跑起来,那些函数也不存在 ===")
|
||||
ns2 = S.load("def probe():\n return 1\n", '<probe>', {})
|
||||
for bad in ('open', 'eval', 'exec', '__import__', 'getattr'):
|
||||
check(f"脚本里拿不到 {bad}", bad not in ns2['__builtins__'])
|
||||
|
||||
print("\n=== 6. ★ 诚实性检查:哪些**真的挡不住** ===")
|
||||
#
|
||||
# 文档里写着"挡手滑不挡有意"。这句必须是真的 —— 一个只测"能挡住"的
|
||||
# 探针会让人误以为这是真沙箱,从而在导入警告里写"安全沙箱,请放心导入"。
|
||||
# 所以这里专门测它**漏**的地方。
|
||||
|
||||
# 6a. 第一层是**文本扫描**,不是语义分析 —— 拼出来的双下划线它看不见
|
||||
sneaky = 'D = "_" * 2\n\ndef on_turn(a, b):\n return D\n'
|
||||
check("拼出来的双下划线能过第一层(证明扫描是文本级的)", rejected(sneaky) == '',
|
||||
"居然被拦了 —— 那说明扫描比我想的强,文档该改")
|
||||
print(" → 只要不把 `__` 直接写进源码,第一层就形同虚设。")
|
||||
|
||||
# 6b. 真正的防线是"没有 getattr / __import__"—— 但它挡不住资源耗尽
|
||||
check("没有资源限制:死循环只能靠超时兜底,不是沙箱挡的",
|
||||
'while True' not in str(S.DANGEROUS))
|
||||
print(" → 内存同理:`[0] * 10**9` 能吃掉几百 MB。")
|
||||
print(" 这些**都挡不住**,所以导入警告不能写'安全沙箱'。")
|
||||
|
||||
# 6c. 确认警告文案里没有虚假承诺
|
||||
warn = S.IMPORT_WARNING
|
||||
check("警告里**没有**'安全沙箱'这类虚假承诺", '安全沙箱' not in warn)
|
||||
check("警告里明说了'不是真正的沙箱'", '不是' in warn and '沙箱' in warn, warn[:60])
|
||||
check("警告里明说了只导入信得过的来源", '信得过' in warn)
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for f in fails:
|
||||
print(" -", f)
|
||||
return 1
|
||||
print("✅ 全部通过")
|
||||
return 0
|
||||
|
||||
|
||||
def _raises_keyerror(ns):
|
||||
try:
|
||||
S.call(ns, 'on_turn')
|
||||
return False
|
||||
except KeyError:
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user