Skip to content

[Bug]: TLS handshake hangs when MySQL SSLRequest and ClientHello arrive together #29928

Closed

Description

@dengn

Is there an existing issue for the same bug?

  • I searched existing open and closed issues for this reproducer.

Branch Name

main

Commit ID

2726fb4

Other Environment Information

Linux x86_64, 4 CPU quota / 32 GiB memory, a single local mo-service running LOG/TN/CN with DISK-V2 file services. Built with Go 1.27.1. All data and credentials below are synthetic local test fixtures.

Actual Behavior

Valid MySQL TLS connections hang during the SSLRequest-to-TLS transition. With the same SSLRequest, ClientHello and trusted certificate:

Transport timing Results
One sendall containing SSLRequest followed by ClientHello 40/40 handshake failures at the 2-second client timeout
Two sendall calls separated by 50 ms 40/40 successful TLS handshakes

An additional ordinary PyMySQL probe failed on 6/30 serial and 57/100 concurrent valid TLS connections. The full TLS batch had 620 handshake failures among 4,000 positive configurations. Negative cases timing out before certificate verification were retained as unexpected transport failures, not counted as successful certificate rejection.

_ssl.c:993: The handshake operation timed out
[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol

The MemoryBIO reproducer stops after TLS negotiation, before MySQL authentication; it does not depend on PyMySQL's authentication logic.

Expected Behavior

Receiving SSLRequest and ClientHello together should be equivalent to receiving them in separate TCP reads. A valid client must not require an artificial delay.

Steps to Reproduce

Configure the local frontend with a locally CA-signed server certificate whose SAN includes localhost and 127.0.0.1:

[cn.frontend]
enableTls = true
tlsCaFile = "/path/to/ca.crt"
tlsCertFile = "/path/to/server.crt"
tlsKeyFile = "/path/to/server.key"

Run the script as: python tls_coalescing_repro.py /path/to/ca.crt.
PyMySQL is used only for protocol constants; TLS itself uses Python ssl.MemoryBIO. The client requires no private key.

import socket,ssl,struct,time,json,concurrent.futures,collections,sys
from pathlib import Path
from pymysql.constants import CLIENT
P=Path.cwd();CAFILE=sys.argv[1]
def readall(s,n):
 b=b''
 while len(b)<n:
  x=s.recv(n-len(b))
  if not x:raise EOFError('peer closed')
  b+=x
 return b
def one(mode,i):
 s=None;t=time.monotonic();status='pass';err=None
 try:
  s=socket.create_connection(('127.0.0.1',6001),timeout=2);h=readall(s,4);readall(s,int.from_bytes(h[:3],'little'))
  ib,ob=ssl.MemoryBIO(),ssl.MemoryBIO();ctx=ssl.create_default_context(cafile=CAFILE);tls=ctx.wrap_bio(ib,ob,server_hostname='localhost')
  try:tls.do_handshake()
  except ssl.SSLWantReadError:pass
  hello=ob.read();flags=CLIENT.PROTOCOL_41|CLIENT.SSL|CLIENT.SECURE_CONNECTION|CLIENT.LONG_PASSWORD|CLIENT.LONG_FLAG|CLIENT.TRANSACTIONS;payload=struct.pack('<IIB23s',flags,16777216,45,b'');packet=len(payload).to_bytes(3,'little')+b'\x01'+payload
  if mode=='coalesced':s.sendall(packet+hello)
  else:s.sendall(packet);time.sleep(.05);s.sendall(hello)
  while True:
   try:tls.do_handshake();break
   except ssl.SSLWantReadError:
    outgoing=ob.read()
    if outgoing:s.sendall(outgoing)
    incoming=s.recv(65536)
    if not incoming:raise EOFError('server closed before TLS completion')
    ib.write(incoming)
  final=ob.read()
  if final:s.sendall(final)
 except Exception as e:status='handshake_failed';err=str(e)
 finally:
  if s:s.close()
 return {'mode':mode,'id':i,'status':status,'error':err,'seconds':time.monotonic()-t}
rows=[]
for mode in ['coalesced','separated']:
 with concurrent.futures.ThreadPoolExecutor(8) as ex:r=list(ex.map(lambda i:one(mode,i),range(40)))
 rows+=r;print(mode,collections.Counter(x['status'] for x in r),flush=True)
(P/'tls-coalescing-repro.json').write_text(json.dumps(rows,indent=2))

Additional information

Suspected root cause, not yet verified by a fix: mysql_buffer.go can pre-read ClientHello bytes after SSLRequest, while RawConn returns the underlying net.Conn. server.go passes RawConn directly to tls.Server, potentially bypassing bytes already buffered by Conn.

No panic, successful TLS downgrade or authorization bypass was observed.

Activity

  1. added
    kind/bug
    on Oct 12, 2026
  2. daviszhen commented on Oct 16, 2026

    @daviszhen
    Contributor

    Local main validation (2026-10-16)

    Validated against MatrixOne upstream/main at b24d1b311555e0b6f3d56eb37f9a2e9617e9a5b7.

    The targeted frontend regressions all pass, including TestConnForTLSCoalescedClientHello, TestConnForTLSPreservesBufferedBytes, TestConnForTLSWithoutBufferedBytesUsesRawConnection, and TestConnectionPeerClosedAfterBufferedTLSUpgrade.

    The default local Docker proxy does not advertise CLIENT_SSL, so a real TLS handshake could not be exercised in this cluster. The direct coalesced-byte regression passes; a TLS-enabled environment should perform final integration validation.

  3. daviszhen commented on Oct 16, 2026

    @daviszhen
    Contributor

    Single-process Docker validation (2026-10-16)

    Follow-up to the earlier multi-CN note: I repeated the test with a single-process -launch MatrixOne instance from upstream/main at b24d1b311555e0b6f3d56eb37f9a2e9617e9a5b7.

    Configuration:

    • local single-process LOG/TN/CN;
    • frontend TLS enabled with a local CA-signed certificate;
    • direct CN endpoint on 127.0.0.1:16003;
    • the initial handshake advertised CLIENT_SSL.

    Using a Python ssl.MemoryBIO client:

    • 40/40 coalesced connections, with the MySQL SSLRequest and TLS ClientHello sent in one sendall, completed TLS successfully;
    • 40/40 separated connections, with a 50 ms delay between SSLRequest and ClientHello, completed TLS successfully;
    • maximum observed handshake time was about 13 ms for coalesced mode and 59 ms for separated mode;
    • MatrixOne logs recorded non-zero UpgradeTLS durations for the connections.

    Therefore the #29928 coalesced SSLRequest/ClientHello hang is not reproducible on current main in the single-process TLS-enabled configuration.

  4. Ariznawlll commented on Oct 16, 2026

    @Ariznawlll
    Collaborator

    测试版本

    • 分支:官方 main
    • commit:b24d1b311555e0b6f3d56eb37f9a2e9617e9a5b7;修复 PR #29996 的 merge commit 2f43deefb88494cb3f4f38bb9ff3b1601dfbec1e 已确认是该 main SHA 的祖先。
    • 部署方式:隔离 worktree 自编译单进程 mo-service,1 CN / 1 TN / 1 LogService,独立 MySQL 端口 38001;CN 启用 TLS,使用仅供本地测试、含 localhost/127.0.0.1 SAN 的临时证书及独立信任锚。
    • 测试日期:2026-10-16

    原问题验证

    按原 issue 的 MySQL SSLRequest + Python ssl.MemoryBIO ClientHello 协议复现,把两段字节放进同一次 sendall。3 轮、每轮 8 线程并发 40 次,合计 120/120 次 TLS 握手成功,单轮最长约 11–14 ms;原故障为同包 40/40 超时。握手真正协商出 TLS 版本,CN greeting 显式检查了 CLIENT_SSL,没有把未启用 TLS 的环境误记为通过。

    Happy Path 覆盖

    1. SSLRequest 与 ClientHello 分两次发送、间隔 50 ms 的对照,同样 3 轮合计 120/120 成功,单轮最长约 59–70 ms。
    2. 并发批次后继续同包握手,每轮 1/1 成功;MySQL CLI 使用 VERIFY_IDENTITY 和正确 CA 完成认证并返回 SELECT 1 = 1。明文连接对照也返回 1。

    Unhappy Path 覆盖

    1. 用不受信任的另一个本地 CA 做 VERIFY_IDENTITY,客户端按预期返回 2026 certificate verify failed,没有把证书拒绝误判为握手修复失败。
    2. 上述失败之后用正确 CA 再连,SELECT 1 = 1;CN 仍正常,无崩溃或不可用。TLS 握手测试不写用户数据,临时证书和隔离服务仅用于本地验收。

    白盒验证

    修复 PR 包含前端缓冲字节交接、同包 ClientHello 与连接关闭路径的 Go 回归;本轮以独立真实 TLS 协议验收为主,未单独重跑 Go UT / -race。研发此前的定向 UT 结果见 issue 评论。

    回归测试

    遵照不再修改 #237 的要求,已新建 MOTR 汇总 PR #247,包含 script/14_issue_regression/issue_29928_tls_coalesced.py 和稳定输出;MOTR 定向 3/3,每轮严格断言同包 40/40、分包 40/40、批后同包 1/1。该场景要求 TLS-enabled CN 和 MO_TLS_CA_FILE,普通非 TLS 环境会明确 skip,不能计作成功。PR 尚未合入;完整 suite 和共享集成 CI 未执行,后续继续跟踪。

    测试证据

    • MOTR 回归脚本与固定断言(提交 76d264e2d52a19c5b371afc6d51675121b411f8d)。
    • 本轮独立 TLS 实例的定向 MOTR 比较:3/3 成功;原始协议同包 120/120、分包 120/120,证书错误后正确 CA 连接成功。

    测试结论

    测试通过。

  5. daviszhen commented on Oct 20, 2026

    @daviszhen
    Contributor

    最新 main 验证(2026-10-20)

    基线:309f618995af4ee23e3b9149365f4af77264090d;关联修复 PR:#29996。

    结论:原问题已解决。exact-main TLS coalesced ClientHello 单元测试及既有集成测试通过,TLS 握手不会因同一 TCP 读取中携带完整 ClientHello 而失败。

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

Metadata

Metadata

Assignees

Labels

kind/bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions