"""规则脚本沙箱的探针(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, '', {}) 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, '', {}) 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', '', '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", '', {}) 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())