Xray-core icon indicating copy to clipboard operation
Xray-core copied to clipboard

[Vision] direct copy 后外层 TLS 的 close_notify 泄入内层字节流, 内层报 bad record MAC

Open yx64 opened this issue 2 months ago • 7 comments

完整性要求

  • [x] 我读完了 issue 模板中的所有注释,确保填写符合要求。
  • [x] 我保证阅读了文档,了解所有我编写的配置文件项的含义,而不是大量堆砌看似有用的选项或默认值。
  • [x] 我提供了完整的配置文件和日志,而不是出于自己的判断只给出截取的部分。
  • [x] 我搜索了 issues,找到了症状相同的 #4878(一年多未定位到根因)。另开一条的理由写在下面第一段。
  • [x] 问题在 Release 最新的版本上可以成功复现(双端 Xray 26.9.9;26.7.28 上结果逐格相同)

描述

English summary, including the full reproduction matrix, is at the bottom of this issue.

先说与 #4878 的关系。 那条 issue 的症状与本条一致,但它是"浏览网页时几十分钟偶发一次", 标题也是症状而不是机制;本条是确定性复现,有单机自包含的复现步骤和源码定位,所以另开 一条以便被搜到和被引用。我不声称能结掉 #4878 —— 那条线程跨了一年多、来源很杂,其中 至少一例作者自己后来确认是别的原因。但它里面那条"使用 claude code 之类的工具时上下文较大 100% 报错"的报告,形态与本条完全一致。

根因。 Vision 识别出内层是 TLS 1.3 之后会切到 direct copy,两端穿透外层 TLS / REALITY 对象,直接读写它底下的裸 TCP 连接。但那个外层对象并没有被拆掉 —— 连接收尾时它的 Close() 仍按 TLS 语义往同一个 socket 上写一条加密的 close_notify。

对端此时正在裸读,无法把它与被转发的载荷区分开,于是把这 24 字节原样交给内层 TLS 端点。 内层端点用内层密钥去认证一条外层密钥加密的记录,必然失败 → bad record MAC。

这条记录在线路上是 17 03 03 00 13 + 19 字节,即 TLS 1.3 下一条加密 alert 的标准尺寸 (2 字节 alert 明文 + 1 字节 inner content type + 16 字节 AEAD tag),内容随外层会话密钥 每条连接都不同。

更一般地说:切换之后,外层 TLS 层写出的任何记录都会破坏内层字节流,close_notify 只是其中必然发生的那一条。

与 #5737 的关系:不是同一处。 那个 PR(2026-03-22 合并,已含在 26.7.28 及之后)修的是 切换时的竞态 —— 把 inbound.CanSpliceCopy = 1 推迟到本次写入完成之后,避免与并发的 direct write 抢同一条 TCP 连接。本条是收尾时外层对象自己往线路上写了一条记录,与切换 时机无关。下面的复现在 26.9.9 和 26.7.28 上逐格相同。

机制(三处)

穿透外层做 I/O —— proxy/proxy.go 的 UnwrapRawConn:

if xc, ok := conn.(*tls.Conn); ok {
    conn = xc.NetConn()
} else if realityConn, ok := conn.(*reality.Conn); ok {
    conn = realityConn.NetConn()
}

切换时把写入端整个换到裸连接上 —— 同文件 VisionWriter.WriteMultiBuffer:

if *switchToDirectCopy {
    ...
    rawConn, _, writerCounter := UnwrapRawConn(w.conn)
    w.Writer = buf.NewWriter(rawConn)
    *switchToDirectCopy = false
}

而外层对象收尾时仍然写 alert —— crypto/tls 与 XTLS/REALITY 的 (*Conn).Close:

var alertErr error
if c.isHandshakeComplete.Load() {
    if err := c.closeNotify(); err != nil { ... }
}
if err := c.conn.Close(); err != nil { return err }

w.conn 从未被替换,也没有任何地方抑制这条 alert —— 仓内搜 close_notify / closeNotify / alertCloseNotify 均无命中。

为什么内层 TLS 1.2 不触发

XtlsFilterTls 只在内层 ServerHello 里找到 TLS 1.3 的 supported_versions 时才置 EnableXtls,而 VisionWriter 只在 EnableXtls 为真时才 *switchToDirectCopy = true。 内层 1.2 → 不切 direct copy → 外层记录层照常工作 → close_notify 被规规矩矩封成外层记录, 由对端外层 TLS 消费掉。下面的对照表里有这一格。

为什么在浏览器上表现为"偶发、刷新即恢复"

这条记录只有在源站关闭一条连接、而客户端恰好还在读它时才会被撞上。多数源站自己会发 close_notify,内层 TLS 用它收尾之后就不再看后面的字节,于是完全无感。所以同一个缺陷在 浏览器上是"几十分钟一次",在会一直读到流末尾的下载器 / CLI 工具上是 100% 必现。

这也解释了几条看起来互相矛盾的报告:换 ws / httpupgrade / XHTTP 就好(不走 direct copy)、 关掉 xtls 就好(同理)、而换新版本不管用(这条路径从未被动过)。

重现方式

整条链路都在一台机器上,不需要 REALITY,不需要任何真实服务器或凭证。外层用普通 security: tls + 自签证书,照样复现 —— 这同时说明缺陷属于 Vision 的 direct copy 本身, 与 REALITY 无关。

四个进程:

源站      node origin.mjs 18443 <polite|abrupt>     内层 TLS 的另一端
服务端    xray run -c server.json                   :18444  vless + xtls-rprx-vision + tls
客户端    xray run -c client.json                   :18081  http 入站
探针      node probe.mjs <url> <proxy|direct>       数流末尾的 TLS 记录条数

一、生成一次性证书(配置里内联的那份就是这么来的;要自己跑请重新生成并替换):

xray tls cert -ca -domain=localhost -name=localhost -org=vision-repro -expire=8760h -json

二、源站 origin.mjs。polite 正常结束 TLS 会话,abrupt 直接 FIN 掉 TCP 不发 close_notify(部分 CDN 就是这样,这一档能让失败直接显形):

// node origin.mjs <port> <polite|abrupt>
import fs from 'node:fs';
import net from 'node:net';
import tls from 'node:tls';

const [PORT, MODE] = process.argv.slice(2);
const ctx = tls.createSecureContext({
  cert: fs.readFileSync('localhost.crt'),
  // `xray tls cert` labels its PKCS#8 EC key as "RSA PRIVATE KEY"; OpenSSL rejects that label.
  key: fs.readFileSync('localhost.key', 'utf8').replaceAll('RSA PRIVATE KEY', 'PRIVATE KEY'),
  minVersion: 'TLSv1.2'
});

net.createServer((raw) => {
  const sock = new tls.TLSSocket(raw, { isServer: true, secureContext: ctx });
  sock.on('error', () => {});
  raw.on('error', () => {});
  sock.once('data', () => {
    const body = 'x'.repeat(4096);
    sock.write(
      `HTTP/1.1 200 OK\r\nContent-Length: ${body.length}\r\nConnection: close\r\n\r\n${body}`,
      () => (MODE === 'abrupt' ? raw.end() : sock.end())
    );
  });
}).listen(Number(PORT), '127.0.0.1', () => console.log(`origin listening on ${PORT} (${MODE})`));

三、探针 probe.mjs。它在 CONNECT 隧道与本地 TLS 端点之间插一个透传 Duplex,旁录 服务器方向的原始字节并按记录头逐条切帧。不解密任何东西 —— TLS 记录头是明文,所以既 不需要会话密钥也不需要抓包:

// node probe.mjs <https-url> <http://proxy:port|direct> [maxTlsVersion]
// Needs Node 18+ (top-level await, Array.prototype.at).
import http from 'node:http';
import net from 'node:net';
import tls from 'node:tls';
import { Duplex } from 'node:stream';

const [URL_ARG, PROXY_ARG, TLSMAX] = process.argv.slice(2);
const target = new URL(URL_ARG);
const proxy = PROXY_ARG === 'direct' ? null : new URL(PROXY_ARG);
const port = Number(target.port || 443);

const raw = await (PROXY_ARG === 'direct'
  ? new Promise((res, rej) => {
      const s = net.connect(port, target.hostname);
      s.once('connect', () => res(s)); s.once('error', rej);
    })
  : new Promise((res, rej) => {
      const creq = http.request({ host: proxy.hostname, port: Number(proxy.port),
        method: 'CONNECT', path: `${target.hostname}:${port}` });
      creq.end();
      creq.once('connect', (r, s) => r.statusCode === 200 ? res(s) : rej(new Error(`CONNECT ${r.statusCode}`)));
      creq.once('error', rej);
    }));

// The boundary that matters is the tunnel socket reaching EOF, not the TLS layer
// emitting 'end' -- the extra record can arrive after the inner stream is done.
let onEof;
const eof = new Promise((r) => (onEof = r));

let pending = Buffer.alloc(0);
const recs = [];
class Tap extends Duplex {
  constructor(s) {
    super();
    this.s = s;
    s.on('data', (c) => {
      pending = Buffer.concat([pending, c]);
      while (pending.length >= 5 && pending.length >= 5 + pending.readUInt16BE(3)) {
        const len = pending.readUInt16BE(3);
        recs.push({ type: pending[0], len, hex: len <= 64 ? pending.subarray(5, 5 + len).toString('hex') : '' });
        pending = pending.subarray(5 + len);
      }
      if (!this.push(c)) s.pause();
    });
    s.on('end', () => { this.push(null); onEof(); });
    s.on('close', onEof);
    s.on('error', (e) => { this.destroy(e); onEof(); });
  }
  _read() { this.s.resume(); }
  _write(c, e, cb) { this.s.write(c, e, cb); }
  _final(cb) { this.s.end(cb); }
}

let first = null;
const sock = tls.connect({ socket: new Tap(raw), servername: target.hostname,
  ...(TLSMAX ? { maxVersion: TLSMAX } : {}) });
sock.on('error', (e) => { if (!first) first = e.message.split('\n')[0]; });
await new Promise((res, rej) => { sock.once('secureConnect', res); sock.once('error', rej); });
const proto = sock.getProtocol();

sock.write(`GET ${target.pathname}${target.search} HTTP/1.1\r\nHost: ${target.host}\r\nConnection: close\r\n\r\n`);
let body = 0;
sock.on('data', (c) => { body += c.length; });
await eof;
sock.destroy();

console.log(`proto=${proto} body=${body} records=${recs.length} unframed_tail=${pending.length}`);
console.log('last 4 records (type/len):', recs.slice(-4).map((r) => `${r.type}/${r.len}`).join(' '));
console.log('last record body:', recs.at(-1).hex || '(long)');
console.log('first TLS error:', first ?? 'none');

四、跑(探针要信任那张自签证书):

export NODE_EXTRA_CA_CERTS=./localhost.crt     # Windows cmd: set NODE_EXTRA_CA_CERTS=localhost.crt
node probe.mjs https://localhost:18443/ direct
node probe.mjs https://localhost:18443/ http://127.0.0.1:18081
node probe.mjs https://localhost:18443/ http://127.0.0.1:18081 TLSv1.2

下面贴的日志是在 Windows 上采的。这条路径与平台无关 —— 写出那条 alert 的是 Go 的 TLS 实现本身;真实链路那一侧的落地是 Linux,行为相同。

实测结果

源站收尾 路径 记录数 末尾四条 (type/len) 内层 TLS
发 close_notify 直连 10 23/250 23/250 23/4173 23/19 正常
发 close_notify 经 Vision 11 23/250 23/4173 **23/19 23/19** 正常(停在真的那条上)
发 close_notify 经 Vision,内层 1.2 9 20/1 22/40 23/4180 21/26 正常
不发 close_notify 直连 9 23/69 23/250 23/250 23/4173 正常
不发 close_notify 经 Vision 10 23/250 23/250 23/4173 **23/19** bad record mac
不发 close_notify 经 Vision,内层 1.2 8 22/170 20/1 22/40 23/4180 正常

六格 unframed_tail 全部为 0,即整条字节流正好切成整数条记录,末条记录不是切错位置的产物。

经 Vision 比直连整整多出一条记录,而且只在内层协商到 TLS 1.3 时多。源站自己发的 close_notify 已经在了,代理仍然要再加一条。那 19 字节每条连接都不同:

b31c96fda5348fceba33ae6a6ba7db790501ee
058bbad4370e11db397462284941a2c906b407
cdbf8d9bf41191eb9b7e745859801c97efb4ee

复现时会撞到的四个与本缺陷无关的门槛

  • 服务端的 freedom 出站默认阻断私有地址,打到回环源站会被 blackhole 三十多秒。 下面的服务端配置里用 finalRules 显式放行了 127.0.0.1/32 与 ::1/128
  • localhost 在本机可能先解析到 ::1,而 origin.mjs 只监听 IPv4。服务端配置里用 sockopt.domainStrategy: "UseIPv4" 固定下来(用 freedom.domainStrategy 会触发弃用告警)
  • xray tls cert 生成的私钥标签写的是 RSA PRIVATE KEY,里面其实是 PKCS#8 的 EC 私钥, OpenSSL 直接拒收(上面的 origin.mjs 里改了标签)
  • 客户端的 allowInsecure 已被移除;改用内联证书 + usage: verify,且必须同时置 disableSystemRoot,否则仍然报 unknown authority

客户端配置


{
  "log": {
    "loglevel": "debug"
  },
  "inbounds": [
    {
      "listen": "127.0.0.1",
      "port": 18081,
      "protocol": "http"
    }
  ],
  "outbounds": [
    {
      "protocol": "vless",
      "settings": {
        "vnext": [
          {
            "address": "127.0.0.1",
            "port": 18444,
            "users": [
              {
                "id": "87b3707b-3c57-48a0-9296-3a5329621a7a",
                "encryption": "none",
                "flow": "xtls-rprx-vision"
              }
            ]
          }
        ]
      },
      "streamSettings": {
        "network": "tcp",
        "security": "tls",
        "tlsSettings": {
          "serverName": "localhost",
          "certificates": [
            {
              "usage": "verify",
              "certificate": [
                "-----BEGIN CERTIFICATE-----",
                "MIIBwzCCAWigAwIBAgIRAJef9XbtCGB7FhAAN5KiA2MwCgYIKoZIzj0EAwIwKzEV",
                "MBMGA1UEChMMdmlzaW9uLXJlcHJvMRIwEAYDVQQDEwlsb2NhbGhvc3QwHhcNMjYw",
                "OTIxMDA1MDU4WhcNMjcwOTIxMDE1MDU4WjArMRUwEwYDVQQKEwx2aXNpb24tcmVw",
                "cm8xEjAQBgNVBAMTCWxvY2FsaG9zdDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA",
                "BIKrSU+bF4dBqJ82fWG+hODbrgZcyh1C4qo5RVQojD+xqXdeFvvLJPSrsCn95Gxf",
                "KgSSHJzFyswHGiP0xwUNsESjbTBrMA4GA1UdDwEB/wQEAwICpDATBgNVHSUEDDAK",
                "BggrBgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBREU1KFlIgn/L/G",
                "d5IFuhYjeSg2fjAUBgNVHREEDTALgglsb2NhbGhvc3QwCgYIKoZIzj0EAwIDSQAw",
                "RgIhAKDKM7Q1SvU2jWkMbUOZkLb0Ad3C7MoPSt4DMKm7w8hgAiEApOG3TTi/xbDr",
                "rycPg2QP1/kQJ6lMdnu1z1Ce0dXrovc=",
                "-----END CERTIFICATE-----"
              ]
            }
          ],
          "disableSystemRoot": true
        }
      }
    }
  ]
}

服务端配置


{
  "log": {
    "loglevel": "debug"
  },
  "inbounds": [
    {
      "listen": "127.0.0.1",
      "port": 18444,
      "protocol": "vless",
      "settings": {
        "clients": [
          {
            "id": "87b3707b-3c57-48a0-9296-3a5329621a7a",
            "flow": "xtls-rprx-vision"
          }
        ],
        "decryption": "none"
      },
      "streamSettings": {
        "network": "tcp",
        "security": "tls",
        "tlsSettings": {
          "certificates": [
            {
              "certificate": [
                "-----BEGIN CERTIFICATE-----",
                "MIIBwzCCAWigAwIBAgIRAJef9XbtCGB7FhAAN5KiA2MwCgYIKoZIzj0EAwIwKzEV",
                "MBMGA1UEChMMdmlzaW9uLXJlcHJvMRIwEAYDVQQDEwlsb2NhbGhvc3QwHhcNMjYw",
                "OTIxMDA1MDU4WhcNMjcwOTIxMDE1MDU4WjArMRUwEwYDVQQKEwx2aXNpb24tcmVw",
                "cm8xEjAQBgNVBAMTCWxvY2FsaG9zdDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA",
                "BIKrSU+bF4dBqJ82fWG+hODbrgZcyh1C4qo5RVQojD+xqXdeFvvLJPSrsCn95Gxf",
                "KgSSHJzFyswHGiP0xwUNsESjbTBrMA4GA1UdDwEB/wQEAwICpDATBgNVHSUEDDAK",
                "BggrBgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBREU1KFlIgn/L/G",
                "d5IFuhYjeSg2fjAUBgNVHREEDTALgglsb2NhbGhvc3QwCgYIKoZIzj0EAwIDSQAw",
                "RgIhAKDKM7Q1SvU2jWkMbUOZkLb0Ad3C7MoPSt4DMKm7w8hgAiEApOG3TTi/xbDr",
                "rycPg2QP1/kQJ6lMdnu1z1Ce0dXrovc=",
                "-----END CERTIFICATE-----"
              ],
              "key": [
                "-----BEGIN RSA PRIVATE KEY-----",
                "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgAIuSt+XYO0kP75tF",
                "Jx+IsaHclMygonpDVyTbA6ategahRANCAASCq0lPmxeHQaifNn1hvoTg264GXMod",
                "QuKqOUVUKIw/sal3Xhb7yyT0q7Ap/eRsXyoEkhycxcrMBxoj9McFDbBE",
                "-----END RSA PRIVATE KEY-----"
              ]
            }
          ]
        }
      }
    }
  ],
  "outbounds": [
    {
      "protocol": "freedom",
      "settings": {
        "finalRules": [
          {
            "action": "allow",
            "ip": [
              "127.0.0.1/32",
              "::1/128"
            ]
          }
        ]
      },
      "streamSettings": {
        "sockopt": {
          "domainStrategy": "UseIPv4"
        }
      }
    }
  ]
}

客户端日志

loglevel: debug。这一次是"源站不发 close_notify + 经 Vision"那一格,探针报 bad record mac。 注意 command 2(即 CommandPaddingDirect)与随后的 CopyRawConn —— direct copy 确实切了。


Xray 26.9.9 (Xray, Penetrates Everything.) 52a412d (go1.27.1 windows/amd64)
A unified platform for anti-censorship.
2026/09/21 10:24:55.686432 [Info] infra/conf/serial: Reading config: &{Name:client.json Format:json}
2026/09/21 10:24:55.688005 [Debug] app/log: Logger started
2026/09/21 10:24:55.688005 [Debug] app/proxyman/inbound: creating stream worker on 127.0.0.1:18081
2026/09/21 10:24:55.690129 [Info] transport/internet/tcp: listening TCP on 127.0.0.1:18081
2026/09/21 10:24:55.690658 [Warning] core: Xray 26.9.9 started
2026/09/21 10:24:57.741644 [Info] [3497087437] proxy/http: request to Method [CONNECT] Host [localhost:18443] with URL [//localhost:18443]
2026/09/21 10:24:57.744794 [Info] [3497087437] app/dispatcher: default route for tcp:localhost:18443
2026/09/21 10:24:57.744794 [Info] [3497087437] transport/internet/tcp: dialing TCP to tcp:127.0.0.1:18444
2026/09/21 10:24:57.744794 [Debug] [3497087437] transport/internet: dialing to tcp:127.0.0.1:18444
2026/09/21 10:24:57.745803 [Info] [3497087437] proxy/vless/outbound: tunneling request to tcp:localhost:18443 via 127.0.0.1:18444
2026/09/21 10:24:57.741644 from 127.0.0.1:58578 accepted //localhost:18443
2026/09/21 10:24:57.754098 [Debug] [3497087437] proxy: XtlsFilterTls found tls client hello! 1586
2026/09/21 10:24:57.754605 [Debug] [3497087437] proxy: XtlsPadding 1586 157 0
2026/09/21 10:24:57.782235 [Debug] [3497087437] proxy: Xtls Unpadding new block, content 1914 padding 62 command 0
2026/09/21 10:24:57.782807 [Debug] [3497087437] proxy: XtlsFilterTls found tls 1.3! 1163 TLS_AES_256_GCM_SHA384
2026/09/21 10:24:57.787873 [Debug] [3497087437] proxy: XtlsPadding 80 1029 0
2026/09/21 10:24:57.788383 [Debug] [3497087437] proxy: XtlsPadding 82 889 2
2026/09/21 10:24:57.788927 [Debug] [3497087437] proxy: Xtls Unpadding new block, content 510 padding 621 command 2
2026/09/21 10:24:57.788927 [Debug] [3497087437] proxy: CopyRawConn (maybe) readv

服务端日志


Xray 26.9.9 (Xray, Penetrates Everything.) 52a412d (go1.27.1 windows/amd64)
A unified platform for anti-censorship.
2026/09/21 10:24:55.684843 [Info] infra/conf/serial: Reading config: &{Name:server.json Format:json}
2026/09/21 10:24:55.687486 [Debug] app/log: Logger started
2026/09/21 10:24:55.688005 [Debug] app/proxyman/inbound: creating stream worker on 127.0.0.1:18444
2026/09/21 10:24:55.694780 [Info] transport/internet/tcp: listening TCP on 127.0.0.1:18444
2026/09/21 10:24:55.695294 [Warning] core: Xray 26.9.9 started
2026/09/21 10:24:57.754605 [Info] [3878328623] proxy/vless/inbound: firstLen = 1186
2026/09/21 10:24:57.755140 [Info] [3878328623] proxy/vless/inbound: received request for tcp:localhost:18443
2026/09/21 10:24:57.755669 [Info] [3878328623] app/dispatcher: default route for tcp:localhost:18443
2026/09/21 10:24:57.754605 from 127.0.0.1:58579 accepted tcp:localhost:18443
2026/09/21 10:24:57.776014 [Info] [3878328623] transport/internet/tcp: dialing TCP to tcp:localhost:18443
2026/09/21 10:24:57.776541 [Info] [3878328623] transport/internet: replace destination with tcp:127.0.0.1:18443
2026/09/21 10:24:57.777070 [Debug] [3878328623] transport/internet: dialing to tcp:127.0.0.1:18443
2026/09/21 10:24:57.777603 [Info] [3878328623] proxy/freedom: connection opened to tcp:localhost:18443, local endpoint 127.0.0.1:58580, remote endpoint 127.0.0.1:18443
2026/09/21 10:24:57.777603 [Debug] [3878328623] proxy: CopyRawConn (maybe) readv
2026/09/21 10:24:57.778126 [Debug] [3878328623] proxy: Xtls Unpadding new block, content 1586 padding 157 command 0
2026/09/21 10:24:57.778662 [Debug] [3878328623] proxy: XtlsFilterTls found tls client hello! 1115
2026/09/21 10:24:57.782235 [Debug] [3878328623] proxy: XtlsFilterTls found tls 1.3! 1914 TLS_AES_256_GCM_SHA384
2026/09/21 10:24:57.782807 [Debug] [3878328623] proxy: XtlsPadding 1914 62 0
2026/09/21 10:24:57.787873 [Debug] [3878328623] proxy: Xtls Unpadding new block, content 80 padding 1029 command 0
2026/09/21 10:24:57.788383 [Debug] [3878328623] proxy: Xtls Unpadding new block, content 82 padding 889 command 2
2026/09/21 10:24:57.788927 [Debug] [3878328623] proxy: XtlsPadding 510 621 2

真实链路上的旁证

上面的复现是全本地的。同一个缺陷也在真实部署上测过:

  • 落地 Linux + Xray-core 26.3.27,入站 vless + xtls-rprx-vision + security: reality, 客户端 mihomo。约 720 字节的响应即可触发 —— 触发条件与传输量无关,只要读到流末尾

  • 更早一轮 84 MB 下载的覆盖面:客户端 mihomo / Xray-core / sing-box 三种实现均复现, 服务端 Xray-core 与 sing-box 两种实现、两台不同地区的落地均复现

  • 在落地与客户端同时抓同一次连接做字节对账:

    源站 -> 落地服务器      84,039,412 字节   (TCP 序号去重)
    客户端 TLS 层收到        84,039,436 字节   (运行时插桩计数)
                          ──────────────
    差                              24 字节   = 5 (记录头) + 19 (记录体)
    

    代理链路凭空多交付了整整一条记录。

sing-box 侧结构相同:sing-vmess 的 vless/vision.go 构造时把 tlsConn.NetConn() 存进 c.netConn,之后 directRead / directWrite 直接走它 —— 同一个不对称。

这些真实链路上的数据,以及把客户端一侧逐层排除的过程(含自建插桩版 Node 的四轮源码级 验证),最初写在 nodejs/node#66001。我一开始报错了对象,在两端同时抓包对出那 24 字节 之后已自行撤回并更正。那条 issue 里遗留的"注入发生在哪一端",由本条回答。

上行方向同样存在

UplinkWriterDirectCopy 走的是同一套切换,客户端侧外层连接关闭时同样会把一条 close_notify 写进上行裸流,由服务端的 Vision reader 转发给目标站点 —— 目标站点会在请求流末尾收到 24 字节 垃圾。修法要覆盖两个方向。

这一条最初写的是"推断、未实测",后来在进程内量到了,见下方的补充评论。

修法方向

核心是一句话:既然穿透外层做 I/O,就必须连外层的收尾一起接管。

两个方向,具体取舍请维护者定:

  1. 在切换到 direct copy 时记住那个裸连接,收尾时关裸连接而不是关外层对象 —— 外层的 Close() 就不会再往线路上写东西
  2. 给外层连接加一个"已被穿透"的标记,Close() 时跳过 closeNotify()

第 1 种不需要改 REALITY,但要把裸连接的所有权带到 app/proxyman/inbound/worker.go 的 defer conn.Close() 那一层;第 2 种改动面更小但要动 REALITY 与 crypto/tls 两条路径。

我可以按选定的方向提 PR,并在上面那套本地复现和真实链路上各验证一遍。


English summary

Root cause. Once Vision switches to direct copy, both ends bypass the outer TLS/REALITY layer and read/write the underlying TCP socket (UnwrapRawConn returns NetConn()). The outer conn object is still alive, and at teardown its Close() writes an encrypted close_notify alert onto that same socket. The peer is reading raw at that point, so those 24 bytes (17 03 03 00 13 + 19) get forwarded as inner payload. The inner TLS endpoint tries to authenticate a record encrypted under the outer session keys and fails: bad record MAC. More generally, any record the outer TLS layer emits after the switch corrupts the inner stream — close_notify is just the one that always happens.

Self-contained reproduction, one machine, both ends Xray 26.9.9, plain security: tls with a throwaway self-signed cert — no REALITY, no real server, no credentials. That also shows the defect belongs to Vision's direct copy rather than to REALITY. Configs, scripts and debug logs are above; the probe only parses cleartext record headers, so no keys and no packet capture are involved.

  • origin sends close_notify: direct → 10 records ending 23/19; via Vision → 11 records ending 23/19 23/19
  • origin just FINs: direct → 9 records, no trailing alert, no error; via Vision → 10 records, trailing 23/19, bad record MAC
  • inner connection capped at TLS 1.2: the extra record is gone in both modes, because XtlsFilterTls only sets EnableXtls when it sees TLS 1.3 in the inner ServerHello, so direct copy never engages
  • the 19-byte body differs on every connection, consistent with per-connection outer keys

Uplink is affected symmetrically. UplinkWriterDirectCopy uses the same switch, so the client-side outer conn's close_notify lands in the uplink raw stream and is relayed to the origin by the server's Vision reader. A fix needs to cover both directions.

Not the same as #5737. That PR (merged 2026-03-22, already in 26.7.28 and later) fixes a race at switch time — deferring inbound.CanSpliceCopy = 1 until the current write finishes. This one happens at teardown. The matrix above is identical on 26.9.9 and 26.7.28.

Why it looks intermittent in browsers. The record is only hit when the origin closes a connection while the client is still reading it. Origins that send their own close_notify mask it completely. Downloaders and CLI tools that read to end-of-stream hit it every time.

Relation to #4878. Same signature, but that one is "occasional while browsing" and its title names the symptom, not the mechanism. This is filed separately because it is deterministic and has a self-contained repro; I am not claiming it closes #4878.

Fix direction. If you penetrate a layer for I/O, you must take over its teardown too: either close the raw conn instead of the wrapper once direct copy is active, or mark the wrapper as penetrated and skip closeNotify(). Happy to send a PR along whichever direction you prefer.

Provenance. The client-side elimination — including four rounds of source-level instrumentation on a custom Node build — and the two-ended byte reconciliation were originally written up in nodejs/node#66001, which I filed against the wrong project and then retracted myself. The question left open there (which side emits the extra record) is answered here.


AI assistance: this investigation and write-up were done with Claude (Opus 5). Every number above is measured on the reporting host, not estimated.

yx64 avatar Sep 21 '26 02:09 yx64

感觉不无道理,确实可能是外层 TLS/REALITY 由于还拿着底层 conn,它们被 Close() 时又往底层 conn 写数据了,被对端内层 TLS 应用收到了

@yuhan6665 @Fangliding

RPRX avatar Sep 21 '26 03:09 RPRX

补一份 Go 侧的实测。原报告里"那 24 字节是外层 Close() 写的"只有读码支撑,现在在进程内 量到了。

做法:在 Xray 交给 TLS 记录层的那个 conn 上包一层记录写入。难点是归属不是采集 —— UnwrapRawConn 返回的正是这个包装,所以 direct copy 的写入也从同一个对象过,按位置分不开。 解法是在外层 Close() 的调用窗口两端打标记,落在窗口内的写入按构造就是收尾写入。

插桩基于 v26.9.9(52a412d)。两头都对过:未改动的自建版本与官方二进制六格一致, 插桩后的版本再跑六格仍然一致 —— 所以下面的数字不是插桩自己造出来的。

下行,源站不发 close_notify

PROBE conn=1 write len=4178 hex=170303104d...      <- direct copy 中继的内层数据记录
PROBE conn=1 CLOSE-BEGIN
PROBE conn=1 write len=24   hex=1703030013e315d9f9a7f9c1463ed8dd692a166d6d5ef6c4
PROBE conn=1 CLOSE-END

同一次连接,探针在线路上看到的:

last 4 records (type/len): 23/250 23/250 23/4173 23/19
last record body: e315d9f9a7f9c1463ed8dd692a166d6d5ef6c4

逐字节相同,窗口内只此一次写入,长度 24 = 5 + 19。

下行,源站发 close_notify:末尾那两条 23/19 各自的来源

PROBE conn=1 write len=24 hex=1703030013379205148f6c74dbd9b6628ce04fe9fc023eac   <- 中继的"真"close_notify
PROBE conn=1 CLOSE-BEGIN
PROBE conn=1 write len=24 hex=1703030013989dffc073bbb952cb6cbd25e4e25f8f62bc20   <- 外层自己加的
PROBE conn=1 CLOSE-END

探针末条记录是 989dffc0...,即窗口内那条。前一条是中继的,后一条是注入的。

内层 TLS 1.2:那次写入照样发生

PROBE conn=2 write len=4328 hex=17030310e3...      <- 外层记录封装的内层数据(没切 direct copy)
PROBE conn=2 write len=53   hex=1703030030...      <- 外层记录封装的内层 alert
PROBE conn=2 CLOSE-BEGIN
PROBE conn=2 write len=24   hex=1703030013612eba978210d43f655995f31f4cfa1d223d41
PROBE conn=2 CLOSE-END

探针这一档的末尾是 20/1 22/40 23/4180 21/26,没有多余记录。

这一格顺带把一个容易读歪的地方钉死:并不是"TLS 1.2 时外层不写这条告警",它照写不误。 差别只在于对端此时仍按外层记录解帧,于是被正常消费掉。缺陷的形状是"写进了一条已经没人按 外层解析的字节流",而不是"写了不该写的东西"。

上行方向:原文标的"推断、未实测",现在也是实测了

客户端默认走 utls(未配 fingerprint 时 GetFingerprint("") 返回 chrome),把那条入口 一并插桩后:

PROBE conn=1 write len=24 hex=17030300138b28b8f6534bd908a091b9887bc0f5eabd056c   <- 中继的内层 fatal alert
PROBE conn=1 CLOSE-BEGIN
PROBE conn=1 write len=24 hex=1703030013a1c4c79b723e9ce4735247d03f573bfe2fbe91   <- 外层自己加的
PROBE conn=1 CLOSE-END

前一条先证明上行的 direct copy 确实已经生效:若它经外层封装,线路上应是 5 + 24 + 1 + 16 = 46 字节,实际就是 24,说明是原样中继。既然服务端此刻是裸读上行,窗口内那一条同样会被原样 转发给目标站点。

还没量的两处

  • REALITY 那条路径没插桩。 上面量的是 crypto/tls 与 utls 两个入口,REALITY 有自己的 (*Conn).Close。机制同构(UnwrapRawConn 对两者一视同仁),但我没有实测,所以只按同构 推断,不当证据
  • Close() 里"有写入在途就跳过告警"那个分支走没走,没量过。 它可能与某些部署下的间歇性 有关,但这纯属猜测

插桩补丁

只为诊断,不是提交候选:

--- a/transport/internet/tls/tls.go
+++ b/transport/internet/tls/tls.go
@@
+var probeSeq atomic.Uint64
+
+type probeConn struct {
+	net.Conn
+	id uint64
+}
+
+func (p *probeConn) log(what string, b []byte) {
+	if b == nil {
+		fmt.Fprintf(os.Stderr, "PROBE conn=%d %s\n", p.id, what)
+		return
+	}
+	n := min(len(b), 64)
+	fmt.Fprintf(os.Stderr, "PROBE conn=%d %s len=%d hex=%s\n", p.id, what, len(b), hex.EncodeToString(b[:n]))
+}
+
+func (p *probeConn) Write(b []byte) (int, error) {
+	p.log("write", b)
+	return p.Conn.Write(b)
+}
+
+func newProbeConn(c net.Conn, role string) *probeConn {
+	p := &probeConn{Conn: c, id: probeSeq.Add(1)}
+	p.log("open "+role, nil)
+	return p
+}
+
 func (c *Conn) Close() error {
+	if p, ok := c.Conn.NetConn().(*probeConn); ok {
+		p.log("CLOSE-BEGIN", nil)
+		defer p.log("CLOSE-END", nil)
+	}
 	timer := time.AfterFunc(tlsCloseTimeout, func() {

UConn.Close 加同样的标记,Client / Server / UClient 三个入口把传入的 conn 换成 newProbeConn(c, ...)。


AI 披露:本条的排查与撰写由 Claude (Opus 5) 协助完成。上面的每个数字都是在本机实测的,不是估算。

yx64 avatar Sep 21 '26 03:09 yx64

看了下代码逻辑还真的可能就是那个陈年bug的起因(之一?) 牛逼啊

Smallthing avatar Sep 22 '26 07:09 Smallthing

A easy way to reproduce this issue:

curl --http1.1 -x socks5h://127.0.0.1:18080 --ignore-content-length -H 'Connection: close' -o /dev/null https://ipinfo.io

for vision:

curl: (56) OpenSSL SSL_read: OpenSSL/3.6.4: error:0A000119:SSL routines::decryption failed or bad record mac, errno 0

for raw vmess:

curl: (56) OpenSSL SSL_read: OpenSSL/3.6.4: error:0A000126:SSL routines::unexpected eof while reading, errno 0

malash avatar Sep 23 '26 07:09 malash

try this? https://github.com/XTLS/Xray-core/commit/aac80195664e437d420fe39080274344ab28d0e7

Fangliding avatar Sep 25 '26 07:09 Fangliding

@Fangliding Using curl for testing, the issue has been resolved.

malash avatar Sep 26 '26 14:09 malash

按修复提交在本机验证过了,确认已修复。

做法:拉 main 上合并后的 e5e85ca(#6834)和它的父提交 7780db9,同一台机器、同一个 Go(go1.27.1 windows/amd64)各编一份,用两种方法各跑一遍,每格 5 次。tls 那套配置与正文相同,只把日志级别调低并加了一个 socks 入站;这次把 REALITY 也加了进去 —— 正文里说过那条路径我当时没有实测。

一、正文里的探针

源站收尾 路径 修复前:记录数 / 内层 TLS 修复后:记录数 / 内层 TLS
发 close_notify 直连 10 / 正常 10 / 正常
发 close_notify tls + Vision 11 / 正常 10 / 正常
发 close_notify reality + Vision 11 / 正常 10 / 正常
不发 close_notify 直连 9 / 正常 9 / 正常
不发 close_notify tls + Vision 10 / bad record mac(5/5) 9 / 正常(5/5)
不发 close_notify reality + Vision 10 / bad record mac(5/5) 9 / 正常(5/5)

修复后,经 Vision 的每一格在记录条数和末尾四条的 type/len 上都与直连完全相同,多出来的那条 23/19 没有了;unframed_tail 全部为 0。内层限定 TLS 1.2 的四格(tls / reality 各两种收尾)修复前后一致,本来就不走 direct copy。

二、@malash 的 curl 命令

沿用 --http1.1 -x socks5h://... --ignore-content-length -H 'Connection: close' 这组参数,目标分别是本地源站和 ipinfo.io。我这里的 curl 是 LibreSSL 构建,同一种认证失败报的是 bad decrypt 而不是 OpenSSL 的 bad record mac。

这两个源站收尾都不发 close_notify,所以直连本身就会报 (56) Connection closed abruptly;判定标准是走 Vision 时的结果要与直连一致。

目标 路径 修复前 修复后
本地源站 直连 closed abruptly(5/5) closed abruptly(5/5)
本地源站 tls + Vision bad decrypt(4/5),另 1 次 closed abruptly closed abruptly(5/5)
本地源站 reality + Vision bad decrypt(5/5) closed abruptly(5/5)
ipinfo.io 直连 closed abruptly(5/5) closed abruptly(5/5)
ipinfo.io tls + Vision bad decrypt(5/5) closed abruptly(5/5)
ipinfo.io reality + Vision bad decrypt(5/5) closed abruptly(5/5)

修复前那 1 次没撞上的原因没有追。源站正常发 close_notify 时,修复前后 curl 各 15 次都正常退出。

没能验证的

上行没能区分出来。 我在源站一侧也按记录头旁录了客户端方向的字节,但修复前源站同样没有收到多余记录,原因没有再往下追,所以上面的数据不能拿来证明上行。上行只能按代码判断:#6834 在 VisionReader 和 VisionWriter 两个切换点都调用了 SuppressOuterCloseNotify,两个方向都覆盖到了。

感谢 @Fangliding 的修复,也感谢 @malash 给出的 curl 复现。


AI 披露:本条的验证与撰写由 Claude (Opus 5.5) 协助完成。上面的数字都是本机实测的,不是估算。

yx64 avatar Sep 28 '26 01:09 yx64