Skip to content

Lua: Sandbox by default (whitelisted functions); Disable inline scripts for now; Add more checks for security reasons - #7136

Merged
RPRX merged 28 commits into
mainfrom
lua-sandbox
Oct 16, 2026
Merged

RPRX merged 28 commits into
mainfrom
lua-sandbox

Conversation

@Meo597

@Meo597 Meo597 commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator
  • Lua 脚本现默认运行在沙箱内
    原则是零信任策略以预期 Lua 脚本可以被安全的分享、订阅下发随意使用
    因此沙箱的实现是白名单提供有限的函数和库,并进一步防止随机数种子和内存布局探测以被更高级的攻击手段利用
  • 封堵上游 https://github.com/yuin/gopher-lua 错误实现导致的沙箱逃逸问题
  • 出于安全审慎,暂时禁用内联脚本,待沙箱的可靠性经得起历史和人民的检验再开启
  • 经测试,精心构造的配置文件可用于启动 core 的同时还是合法 Lua 脚本
    为防下游校验不严且全盘接收订阅下发,core 本地配置文件和 Lua 脚本穿透后的路径必须是合法扩展名否则拒绝启动
    这同样是出于安全审慎,因为沙箱本就足够安全,且下游订阅实现从不是整个 json/yaml... 而是自行拼装
  • 经测试,精心构造的 geodata 文件可用于分流的同时还是合法 Lua 脚本
    威胁模型是下游接收同一来源的 geodata dns router finalmask 块的订阅,攻击者可依赖特定时序导致 Lua 脚本被下发后启动
    现 core 的 geodata 下载器会写入头 \x12\x01\x00 杜绝此风险,因为它是非法 Lua 字节
    如果下游自己下载 geodata 且来源和订阅都是攻击者,那么还有 core 的扩展名防护和沙箱机制
    这同样是出于安全审慎的预防性措施,因为沙箱足够安全,且此潜在攻击路径对攻击者(你的机场)要求过于苛刻
  • 杂项:顺手发现并修复了精心构造的 geodata 可导致 xray 启动或热更新 geodata 时的 oom 问题,没有安全影响,攻击者只能恶作剧
  • 杂项:降低了 Lua 实例预分配栈大小以降低内存占用
  • 准备了 Lua 脚本公私钥签名机制和特权模式机制,但暂时禁用,同样是出于安全审慎原则
  • 由于零信任策略,因此使 xray api 提供的 slice 只读防止 race
  • 同上,收紧了 https://github.com/layeh/gopher-luar 暴露的方法,要求必须白名单

@RPRX

RPRX commented Oct 13, 2026

Copy link
Copy Markdown
Member

env 未来可能是会包含在“下发订阅”里的,所以不能直接把 lua 的那些敏感操作禁掉吗?比如访问文件和连接网络

@Meo597

Meo597 commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator Author

能,但总感觉被和谐了不太爽
让内联脚本不允许开特权模式?

@Meo597

Meo597 commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator Author

现在仅本地脚本允许特权模式

还发现了一个上游的内存和安全问题
这边封堵了 20c4c8f

@Fangliding

Fangliding commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

理论上一个恶意的lua甚至因为可以访问xray内置dns可以通过dns tunnel获得网络然后挖矿啥的 任意代码执行权限还是太危险了 要么就改成使用lua(特权)功能需要 start 的时候加一个 lua-(privileged) 的 flag

@Meo597

Meo597 commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator Author

主要还是靠下游,核心做啥都没用,意思到了就行

核心本身是安全的,威胁来自于订阅和链接分享

@RPRX

RPRX commented Oct 13, 2026

Copy link
Copy Markdown
Member

那俩敏感权限无条件砍掉吧,虽然只要是放在 Xray-core 内那么似乎做不到完全禁止它联网,对了还要禁掉 exec lua code 这种

@Meo597

Meo597 commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator Author

我觉得特权模式没必要进一步限制
因为矛盾点在于 lua 花活实在是太多了

xray 的 lua 不像游戏里的插件只需要最小沙盒,连 debug string.dump print load 都不给
这些其实都是攻击面,一大堆看似正常的函数都能被拿来利用
在特权模式简单粗暴的禁,总是能找到更多的利用点,封不完的

而且就连 os.exec 也有潜在的实际用途,比如运行时操纵 iptables、节点不通 curl
下个 PR 准备搞全局脚本,订阅事件,控制 xray,先从负载均衡下手

我觉得应该让沙盒模式最小白名单,安全到可以随便被下发订阅,分享链接
特权模式全部放开有足够的扩展性,但没法被下游随意启动(除非故意)
这样只要守好两头就行,而不是跟 lua 花活作斗争

目前本地文件型的没什么攻击面了
恶意程序如果能达成随意写 xray 配置文件,并同时写入一个外部 lua
那他不如自己改 windows 快捷方式或 bashrc
一大堆的地方可以下手攻击面更广

目前的特权模式风险点在 env 上
如果下游非要把位置来源的 lua 写入文件,并且还能接收外部 env 用来给 lua 提权
(这样搞基本就是故意的,没有任何理由这样做)

可以让 XRAY_LUA_PRIVILEGED_PSK 不允许从配置文件读
(说实话不太明白为什么 env 要走配置文件读,一大堆无法生效的)

再进一步就是改为启动参数(用起来麻烦点)

@Meo597

Meo597 commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator Author

或者特权模式 psk 改为公私钥签名脚本
防止本地恶意程序扫、改 lua 利用 xray tun 提权
(有点过度了)

@RPRX

RPRX commented Oct 13, 2026

Copy link
Copy Markdown
Member

其实直接不支持内联 lua 的话就没那么多问题了,然后客户端订阅只修改 Xray 配置,不过你那 geo 自动下载是不是任意文件

@Meo597

Meo597 commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator Author

所以 geodata 只允许下载已经存在的文件,并且目录给限定死了,还抠了半天防逃逸检查

内联脚本的安全性我倒不是特别担心,全锁在最小沙盒里,白名单定好可防可控

倒是目前特权模式设计的 psk 只能防小白复制一份网络大神脚本
公私钥签名 lua 越想越觉得是合理的方案
甚至可以内置一份 Xray LuaHub 仓库的公钥

@RPRX

RPRX commented Oct 13, 2026

Copy link
Copy Markdown
Member

所以 geodata 只允许下载已经存在的文件,并且目录给限定死了,还抠了半天防逃逸检查

盲猜可以下载的文件名是 geosite.dat 然而实际内容是 lua 然后被 Xray 加载

@Meo597

Meo597 commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator Author

基本一秒就没了因为下载后必定立刻重载

@Meo597

Meo597 commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator Author

geodata 那边没有暴露 reload download 那些 api
沙箱下即便能任意下载也没法加载,即便加载也没有权限执行威胁代码

@Meo597

Meo597 commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator Author

还好是 pure go 没有溢出再导致 rce 问题
包稳的

@RPRX

RPRX commented Oct 13, 2026

Copy link
Copy Markdown
Member

基本一秒就没了因为下载后必定立刻重载

配置文件可以根本就没用到 geosite.dat,只为了恶意攻击

@Meo597

Meo597 commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator Author

如果按照之前那样文件模式默认特权,或者说能下发完整 json,这个攻击就成功了

密钥放在启动参数就没办法了

@RPRX

RPRX commented Oct 14, 2026

Copy link
Copy Markdown
Member

沙盒模式现在限制了哪些东西?

@Meo597

Meo597 commented Oct 14, 2026

Copy link
Copy Markdown
Collaborator Author

沙盒模式限制:
系统库、调试库、并发库
动态代码加载
模块加载
lua 元表和函数环境
运行时控制
打印内部消息、探测内存布局
探测随机数种子

@RPRX

RPRX commented Oct 14, 2026

Copy link
Copy Markdown
Member

即使这样,我觉得内联 lua 还是有点危险,要不先暂时禁止了吧,且加载本地 lua 也必须需要签名

@Meo597

Meo597 commented Oct 14, 2026

Copy link
Copy Markdown
Collaborator Author

能用的库和函数都是白名单了

沙盒模式也签名的话有点过度防御了
毕竟 config.json 也没保护

@Meo597

Meo597 commented Oct 14, 2026

Copy link
Copy Markdown
Collaborator Author

然后 go 那边的反射函数也有白名单

@Meo597

Meo597 commented Oct 15, 2026

Copy link
Copy Markdown
Collaborator Author

@RPRX 目前这个 PR 已经是你想要的状态了

NEXT 架构和可编程协议若要继续推进,必须在合理的威胁模型下设计安全架构
(先把规矩立住,路才能越走越宽)

签名、特权模式、内联脚本这些,后续功能演进的时候再说吧

目前我已经燃尽了
(这代码写的烧心)

@svlavr

svlavr commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Astra 6:

@Meo597 Rechecked the latest commit, 03ee3f872f072688599d17f1fd12e3243c063dc2, including the changes made after the previous review and your clarification of the threat model.

The earlier findings should be updated as follows.

  1. The demonstrated DNS-cache mutation is fixed.

    Both Lua DNS interfaces now use read-only IP-slice bindings. The recursive protection also covers the nested IP byte slices.

    Repeated the actual-cache check for all four cases: server:Query and dns.Query, directly and after FilterIPs. Attempts to replace an outer element, change an IP byte, or modify a To4() view are rejected. The stored cache record and subsequent native cache lookup retain the original address.

    This closes the previously demonstrated mutation path while preserving zero-copy access. Deep-copying DNS results is no longer necessary for that finding.

    The existing read-only binding tests also cover iteration, lazy initialization, IP views, masks and recursive slice types.

  2. Signature-based privileged execution is disabled.

    Compile no longer invokes signature verification, so ordinarily constructed programs remain sandboxed.

    An additional check with a correctly signed file and a configured trusted public key confirmed that the script still cannot access io, os.execute, os.getenv or dofile. A malformed signature header also remains an ordinary Lua comment.

    Dormant signing code and the privileged-state branch remain in source, but no ordinary configuration or CLI input was found that can activate that branch. The previous mismatch between the announced sandbox-only direction and executable behavior is therefore closed.

    Both inline prefixes are also rejected before execution.

  3. The configuration-tracker findings no longer apply.

    The process-wide file tracker was reverted. Its unsynchronized slice and permanent registration history are gone, so the previous race and lifetime findings should be withdrawn against this revision.

    The replacement is extension validation for regular configuration files used by run, including checking the resolved symlink target.

    This is a narrower CLI input policy. It is not content authentication or a universal admission check for embedding APIs, HTTP sources, or files downloaded but never submitted to the core. Those boundaries should remain explicit; I am not presenting them as new bypass findings.

  4. Error-address redaction and the restricted time API are implemented.

    The new pcall/xpcall wrappers redact address-like text in caught string errors, including before an xpcall handler receives it. The new protected-call and native-error tests pass.

    The sandbox exposes only os.clock, os.date, os.difftime and os.time. Command execution, environment access and filesystem operations remain unavailable through that table.

  5. A new Windows regression was found: valid regular-file stdin is rejected.

    When stdin: is backed by a regular file, the loader applies filepath.Abs(file.Name()) and filepath.EvalSymlinks. An inherited stdin handle has a synthetic name such as /dev/stdin; that name does not identify the actual backing file on Windows.

    A valid allowed-extension configuration file, passed as the child process's stdin with:

    run -test -format json -c stdin:
    

    fails with exit code 23 before decoding:

    GetFileAttributesEx E:\dev: The system cannot find the file specified.
    

    The identical positive test passes on 9726bbc9 and fails on 03ee3f8.

    The current stdin tests cover pipe success and rejection of a redirected .lua file, but not acceptance of a redirected valid configuration. On this host, the negative case passes because path resolution fails, rather than because the extension is rejected.

    Proposal: choose an explicit stdin policy:

    • Treat stdin: consistently as a byte stream, including redirected regular files, and keep filename restrictions for named local sources.
    • If regular-file stdin must retain extension enforcement, obtain its actual path from the open handle using platform-specific handling. File.Name() is insufficient.

    Add a positive redirected-file test. The negative .lua case should assert the extension-rejection error specifically.

  6. The existing go vet failure remains.

    go vet ./common/lua still reports:

    program.go:38:3: unreachable code
    

    The decoder remains after an unconditional return. Keeping the TODO is sufficient to record possible restoration; removing the unreachable statement would let this check pass.

  7. Smaller initial Lua stacks improve allocation sizing, but do not establish resource quotas.

    NewState now accepts an explicit initial registry size, with DNS and routing using 256 slots. The stack can grow to the configured maximum.

    This reduces the initial stack allocation; no measured process-memory improvement is claimed here. It does not impose a Lua heap budget or limit the total number of active states. Those remain separate existing TODOs, rather than new regressions.

Validation on 03ee3f8:

  • common/lua, common/platform and app/geodata tests passed.
  • Targeted Lua/script tests in DNS and routing passed.
  • Relevant Lua, DNS and routing tests passed with -race.
  • All 12 existing TestRunConfigCommands cases passed.
  • All four actual-cache isolation checks passed.
  • Additional signed-file sandbox and inline-rejection checks passed.
  • The positive regular-file stdin check failed on the new revision and passed on the previous revision.
  • go vet ./common/lua still failed as described above.

The first DNS test run lacked geoip.dat; after supplying the local test assets, the unchanged tests passed. These are Windows host checks, not a full platform or release qualification.

The main previous findings are now closed or withdrawn. The actionable follow-up is the regular-file stdin regression, plus the retained go vet cleanup.

@Meo597

Meo597 commented Oct 15, 2026

Copy link
Copy Markdown
Collaborator Author

pool 的问题需要放到另一个 PR 处理
计划是测量等待和空闲时间来动态伸缩
这样就比较万金油了

@Meo597

Meo597 commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator Author

后缀检测本意就是尽力而为,因为判定 stdin 有没有本地路径非常容易,顺手就做了
主打一个尽力而为,如果它在本地就应该受到约束

不行,有本地路径不意味着一定是本地文件来源
我会放弃对 stdin 的检查
真想绕过一百万种方法,我不想在这种地方堆砌代码

@svlavr

svlavr commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

go vet ./common/lua on bba0ae39 still reports program.go:38:3: unreachable code. I suggest removing the decoder call after return, while keeping the TODO about restoring inline support.

@Meo597

Meo597 commented Oct 15, 2026

Copy link
Copy Markdown
Collaborator Author

Incorrect suggestion

@svlavr

svlavr commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Meo597

Incorrect suggestion

Well, if you say so )) So we don’t forget.

@RPRX

RPRX commented Oct 16, 2026

Copy link
Copy Markdown
Member

准备合并,你记得修改一下 PR 描述 @Meo597

@RPRX RPRX changed the title Lua: Add sandbox mechanism Lua: Sandbox by default (whitelisted functions); Disable inline scripts for now; Add more checks Oct 16, 2026
@RPRX
RPRX merged commit bbfb745 into main Oct 16, 2026
@RPRX RPRX changed the title Lua: Sandbox by default (whitelisted functions); Disable inline scripts for now; Add more checks Lua: Sandbox by default (whitelisted functions); Disable inline scripts for now; Add more checks for security reasons Oct 16, 2026
RPRX pushed a commit that referenced this pull request Oct 16, 2026
@Meo597

Meo597 commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator Author

描述改好了你看看,手打小作文

@Meo597

Meo597 commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator Author

@RPRX 权限的问题我想了一下,可以按能力申请,像手机那样摄像头、相册、网络等分开,最后统一签名
@Fangliding 说的 DNS 隧道的问题就能在合理框架下解决,不申请“任意公网权限”则只能给硬编码的 DoH 通信

具体的实现是,用户不能用命令加参数显式授权,必须是脚本的注解 declare 权限
申请敏感权限时,交互式的命令行可以按 360 卸载风格 反复多次要求授权,各种多重否定句力争把小白用户绕进去
并且问题顺序打乱,确保用户真逐字阅读了
这样避免恶意脚本提供者同时给一条命令让用户去执行

内联脚本永远不可能申请权限,这样自定义协议、自定义 Finalmask 有基础能力可以下发订阅

@svlavr

svlavr commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

What if providers supplied JSON describing behavior according to a predefined set of rules, rather than a ready-made Lua file? A dedicated handler could validate the structure and allowed operations, discard unsupported fields or reject invalid documents, and then generate a Lua script for Xray using trusted templates.

The provider would supply only permitted parameters and rules, with no embedded Lua code; the executable code would be generated on the client side. Some functionality would be restricted, but this could provide a way to support Lua policies from subscriptions now.

@Meo597

Meo597 commented Oct 17, 2026

Copy link
Copy Markdown
Collaborator Author

The expectation is a programmable protocol, where JSON subscriptions will directly deliver Lua scripts—stripped of sensitive permissions—to customize traffic appearances, or even protocols, and perhaps even configure routing and DNS rules.
However, Lua is extremely powerful, and I don't want to restrict it; advanced users should have 100% control over everything in Xray.
This would also mitigate a significant portion of "vibe" issues—for instance, many implementations in the finalmask module or certain PRs for the XHTTP protocol are low-quality "vibes."
There are also several closed PRs where users wanted to customize their own personalized balancers.
All of this requires a reasonable permission model.

@svlavr

svlavr commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

I suggest separating the two: providers get JSON with allowed parameters and rules; users get full Lua scripting. Both approaches can be implemented at the same time without interfering with each other.

Giving providers too much control seems excessive to me: they could go overboard with DNS, routing, and other settings.

For users, we could also put together a separate library of example scripts on GitHub.

@Meo597

Meo597 commented Oct 17, 2026

Copy link
Copy Markdown
Collaborator Author

Yes, that was indeed current design, which is why I refused to delete the signature mechanism and chose to comment it out instead.
RPRX is concerned about its security, and that will take time to verify. Once everything is fully prepared, it will only take a two-line change to add everything back.
Additionally, in subsequent PRs, if I determine that certain APIs involve sensitive operations, I will restrict their capabilities under that permission model to avoid major code refactoring in the future.
The comment above also mentions LuaHub. If RPRX is willing, i could include an official XTLS pubkey. Users could choose to download and use sensitive code that has been reviewed by us, and if RPRX agrees, it could even be made available for inline JSON. All of this is very flexible; the specific extent to which this should be allowed requires extensive discussion, but from a code perspective, it would only require changing a line or two.

@svlavr

svlavr commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

@Meo597 Thanks for the clarification! If you need help with testing through Codex, feel free to reach out here.

@svlavr

svlavr commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

@Meo597

I'm testing how to select the best path for each new connection in my fork.

The first scenario uses one node: I query different DNS resolvers for the destination domain, then test access to the resource through that node using each returned IP address.

The second scenario uses multiple nodes: I repeat this for each node with different DNS resolvers, then choose which path to use for a new connection. The preference can be faster or more stable access.

The main challenge is actually applying that choice: the DNS cache can return a previous IP even after a different option has been selected. Changing the DNS resolver or node alone is not enough—the new connection must actually use the selected path.

Have you considered supporting this scenario through Lua?

@Meo597

Meo597 commented Oct 18, 2026 •

Copy link
Copy Markdown
Collaborator Author

If you need help with testing through Codex, feel free to reach out here.

Thanks, I will reach out if needed.


Have you considered supporting this scenario through Lua?

为了能选择最快 ip 我认为应该使用 happyeyeballs
核心已经内置此能力
只需要你把候选 ip 扩充的较为丰富即可,而不是想办法在 DNS 再做一套探测
smartdns 的理念设计错误

我会进一步修改 Lua 让 splice[] 可以编辑,比如加个 spliceObj:ToTable()
让 DNS 模块支持解析 LTable,因此你可以在 DNS 直接构造任意结果

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants