#6794·Xray-core

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

Author: yx64Created Sep 21, 2026Updated Sep 25, 2026

完整性要求

  • 我读完了 issue 模板中的所有注释,确保填写符合要求。
  • 我保证阅读了文档,了解所有我编写的配置文件项的含义,而不是大量堆砌看似有用的选项或默认值。
  • 我提供了完整的配置文件和日志,而不是出于自己的判断只给出截取的部分。
  • 我搜索了 issues,找到了症状相同的 #4878(一年多未定位到根因)。另开一条的理由写在下面第一段。
  • 问题在 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:

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

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

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

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

go
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 就是这样,这一档能让失败直接显形):

javascript
// 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 记录头是明文,所以既 不需要会话密钥也不需要抓包:

javascript
// 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');

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

bash
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 REALI