Skip to content

feat: opt-in small-segment ServerHello (network.client-mss) - #580

Open
AndreyOsipuk wants to merge 6 commits into
9seconds:masterfrom
AndreyOsipuk:feat/client-mss-upstream
Open

AndreyOsipuk wants to merge 6 commits into
9seconds:masterfrom
AndreyOsipuk:feat/client-mss-upstream

Conversation

@AndreyOsipuk

Copy link
Copy Markdown
Contributor

Some DPI boxes recognise the FakeTLS ServerHello when it arrives in full-size TCP segments and then block the server ip:port, but let the same bytes through when they come in small segments. We hit this on a Russian ISP (Rostelecom): replaying a real ClientHello of Telegram iOS against mtg, only 3 of 8 handshakes completed and the port got banned; with the ServerHello split into 80-byte segments all 8 of 8 completed and the port was not banned. Keeping a small MSS for the whole session works too, but it is slow and multiplies packets per second, so this PR splits only the ServerHello.

Disabled by default:

[network]
client-mss = 92         # 0 (default) disables; 48..1460
client-mss-bulk = 1400  # 0 or 536..65495, 1400 by default when client-mss is set

How it works (Linux only, a no-op with a warning elsewhere):

  • client-mss-bulk > 0: the listening socket gets TCP_MAXSEG = client-mss-bulk; accepted connections inherit it. The ServerHello is written in chunks that fit one segment at MSS = client-mss (minus the timestamps option when it is negotiated: 80 bytes for 92), and each next chunk is written only after the previous one has left the socket queue (tcpi_notsent_bytes == 0). Without that wait the kernel merges chunks once it hits the congestion window or autocorking: at 100 ms RTT 4 KB written in 80-byte chunks left in 13 segments, with the wait in 52. The wait is bounded by the handshake timeout. After the ServerHello nothing changes, the rest of the session uses full-size segments.
  • client-mss-bulk = 0: TCP_MAXSEG = client-mss on the listening socket for the whole session, the same as iptables ... TCPMSS --set-mss on the client SYN (client-mss must then be at least 88, the kernel minimum).
  • Works through the PROXY protocol wrapper (the underlying *net.TCPConn is used); for a non-TCP connection the ServerHello is written as before.

Why not "a small MSS on the listener, then raise it with setsockopt(TCP_MAXSEG)" (or the other way round): on Linux the segment size is fixed during the TCP handshake (mss_clamp), and setsockopt(TCP_MAXSEG) on an established connection only changes user_mss, which no longer affects outgoing segments. Checked on 6.12: listener MSS 92, then setsockopt 1400 - tcpi_snd_mss stays at 80. There is a test for this (TestTCPMaxSegCannotBeRaisedAfterAccept). Hence the bulk MSS goes on the listener and only the ServerHello is split in user space.

The idea and the option names follow client_mss / client_mss_bulk in telemt. This is a separate implementation in Go; the chunking mechanism differs (here the socket MSS is not touched after accept, chunks are paced by tcpi_notsent_bytes).

Documented in example.config.toml. The listener options are read at start.

Tests (Linux, real loopback sockets):

  • the writer: a 4 KB ServerHello leaves in at least one segment per 80-byte chunk while the session stays at tcpi_snd_mss >= 1000; chunks are not merged when the client has a 2 KB receive window and does not read for 300 ms; a real fake.SendServerHello through the writer is parsed as three TLS records; PROXY protocol unwrapping; fallback for non-TCP;
  • the listener: TCP_MAXSEG is advertised in the SYN-ACK, 0 keeps the default, too small values are rejected, and the MSS cannot be raised after accept;
  • end-to-end through the proxy with a real ClientHello snapshot: without client-mss the ServerHello (3-4.5 KB, the size is randomised) arrives in 2 segments, with client-mss = 92 in about 50-60;
  • config parsing and validation (bounds, explicit client-mss-bulk = 0, defaults) and the mapping of the options to listener/ServerHello MSS.

gofmt, go vet ./..., go test -race ./..., GOOS=windows go build ./..., GOOS=darwin go vet ./... and golangci-lint run (v2.12.2) pass.

Some DPI boxes (seen on a Russian ISP) recognise the FakeTLS ServerHello
when it arrives in full-size TCP segments and then block the server
ip:port, but let it through when the same bytes come in small segments,
as with a client MSS of 92. Keeping a small MSS for the whole session is
slow and costs a lot of packets per second, so only the ServerHello is
split.

[network] client-mss (0 disables, 48..1460) and client-mss-bulk (0 or
536..65495, 1400 by default):

- bulk > 0: TCP_MAXSEG = bulk on the listening socket; the ServerHello is
  written in chunks that fit one segment at MSS = client-mss, each chunk
  only after the previous one has left the socket queue
  (tcpi_notsent_bytes = 0), otherwise the kernel merges chunks when it
  hits the congestion window or autocorking;
- bulk = 0: TCP_MAXSEG = client-mss on the listening socket for the whole
  session, like iptables TCPMSS on the client SYN.

The order cannot be reversed (small MSS on the listener, then a larger
one): on an established connection setsockopt(TCP_MAXSEG) does not change
the segment size, mss_clamp is fixed during the TCP handshake (listener
92, then 1400 - tcpi_snd_mss stays at 80). Linux only, a no-op elsewhere.
Disabled by default.
@dolonet

dolonet commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator

Integration note: I checked this patch together with current #577 on a clean upstream clone. They conflict in internal/utils/net_listener.go and internal/cli/run_proxy.go because both add a third NewListener argument (MSS here, logger in #577). Please reconcile that listener signature when updating this branch. For review, the remaining network checks should include a slow/non-reading client respecting the ServerHello deadline, PROXY protocol/wrapper connections, and observed packet sizing; loopback tests alone do not establish the DPI effect across networks. This remains for @9seconds to review.

…enerMSS

NewListener no longer takes the listener MSS. utils.SetListenerMSS sets
TCP_MAXSEG on the already listening socket right after NewListener and
before the PROXY protocol wrapper; accepted connections inherit it the
same way. This keeps the listener constructor free for other changes.
… client-mss

The small-segment ServerHello writer now waits until the same handshake
deadline that is set on the client socket, so a client that never reads
cannot hold the stream past the handshake timeout.

Tests: a non-reading client with a tiny receive window (writer and full
proxy), the handshake behind the PROXY protocol listener (v1 and v2),
tcpi_rcv_mss as an unprivileged signal of the largest received segment,
and an AF_PACKET loopback capture that checks every ServerHello segment
(skipped without CAP_NET_RAW).
@AndreyOsipuk

Copy link
Copy Markdown
Contributor Author

Thanks for checking the two together. In 00657fc I removed the competing parameter: NewListener is back to its upstream signature, and the listener MSS is now set by a separate utils.SetListenerMSS(listener, mss) right after NewListener, before the PROXY protocol wrapper. I test-merged this branch with current #577 in both orders: no conflicts either way, identical trees, and build, vet, -race tests and golangci-lint pass on the result.

f4b7e78 adds the network tests you asked for:

  • a client that never reads: the small-segment write stops at the handshake deadline. It now uses the same deadline that is set on the client socket; before, it computed a new one at ServerHello time, slightly later than the socket deadline;
  • handshakes behind the PROXY protocol listener with v1 and v2 headers;
  • observed segment sizes, both via tcpi_rcv_mss (no privileges needed) and via an AF_PACKET loopback capture that checks every ServerHello segment is <= client-mss (the largest is exactly 92 bytes: 80 payload + 12 option bytes). The capture test is skipped without CAP_NET_RAW.

As you say, loopback tests do not show the DPI effect across networks; that part needs field data and is up to @9seconds.

@AndreyOsipuk

Copy link
Copy Markdown
Contributor Author

Merged current master (with #577 and #578) into the branch; the head is now e087c25. It merged without conflicts, as expected after the NewListener change. The earlier red Test job was TestProxy/TestHTTPSRequest against httpbin.org, which master replaced with the local fixture in #582. On the merge: go vet ./..., go test -race -count=3 ./... (all packages green), GOOS=darwin|windows|freebsd go build ./... and golangci-lint v2.12.2 pass.

@codecov-commenter

codecov-commenter commented Nov 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 81.14286% with 33 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.39%. Comparing base (2026e32) to head (e05e80d).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
mtglib/server_hello_mss_linux.go 75.00% 10 Missing and 7 partials ⚠️
internal/cli/run_proxy.go 0.00% 5 Missing ⚠️
internal/cli/client_mss.go 80.00% 2 Missing and 1 partial ⚠️
internal/config/type_tcp_mss.go 87.50% 1 Missing and 1 partial ⚠️
internal/utils/net_listener_mss.go 90.00% 1 Missing and 1 partial ⚠️
mtglib/proxy.go 83.33% 0 Missing and 2 partials ⚠️
network/sockopts_mss_linux.go 83.33% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #580      +/-   ##
==========================================
+ Coverage   68.31%   69.39%   +1.08%     
==========================================
  Files         112      118       +6     
  Lines        4087     4261     +174     
==========================================
+ Hits         2792     2957     +165     
+ Misses       1146     1143       -3     
- Partials      149      161      +12     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

… queue

Without MSG_EOR the kernel may collapse adjacent small skbs on
retransmission (tcp_retrans_collapse is on by default), so on a lossy path
the retransmitted ServerHello left in full-size segments. Polling
tcpi_notsent_bytes between writes did not prevent that.

Each chunk is now one sendmsg(MSG_EOR|MSG_NOSIGNAL) through RawConn. EAGAIN
waits on the poller under the handshake deadline, EINTR retries, and a
partial send finishes the current chunk, so chunk boundaries stay fixed.

Tests: a fake sendmsg checks the flags and boundaries of every call,
including partial sends, EINTR and EAGAIN; a full send buffer on a real
socket; and a retransmission test that drops incoming packets with a socket
BPF filter and checks that retransmitted segments are not larger than a
chunk (fails on the previous code: 1360 bytes in 3 segments).
@AndreyOsipuk

Copy link
Copy Markdown
Contributor Author

Reworked the splitting in 51c758e: each chunk now goes out with sendmsg(MSG_EOR) instead of a write followed by polling tcpi_notsent_bytes. Without EOR the kernel collapses adjacent small skbs on retransmission (tcp_retrans_collapse is on by default), so on a lossy path the retransmitted ServerHello went out in full-size segments. TestWriteFragmentedRetransmissionIsNotCollapsed reproduces it on the previous code (1360 bytes retransmitted in 3 segments, against 10 segments of 80 bytes now). A full send buffer is handled through RawConn and the poller under the handshake deadline, and partial sends finish the current chunk. New tests cover both, with a fake sendmsg that checks the flags and chunk boundaries of every call. go vet, go test -race ./... on Linux (with CAP_NET_RAW, so the capture tests ran) and golangci-lint pass.

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.

3 participants