From 7bfc7e38c3e49abe60029cc70e6738ce1aa0dd69 Mon Sep 17 00:00:00 2001 From: Andrey Osipuk <45951478+AndreyOsipuk@users.noreply.github.com> Date: Wed, 7 Oct 2026 20:08:12 +0300 Subject: [PATCH 1/5] feat: opt-in small-segment ServerHello (network.client-mss) 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. --- example.config.toml | 13 ++ internal/cli/client_mss.go | 42 ++++ internal/cli/client_mss_test.go | 49 +++++ internal/cli/run_proxy.go | 5 +- internal/config/client_mss_test.go | 85 ++++++++ internal/config/config.go | 79 ++++++- internal/config/parse.go | 4 + internal/config/type_tcp_mss.go | 44 ++++ internal/utils/net_listener.go | 10 +- mtglib/proxy.go | 20 +- mtglib/proxy_client_mss_linux_test.go | 186 ++++++++++++++++ mtglib/proxy_opts.go | 7 + mtglib/server_hello_mss.go | 41 ++++ mtglib/server_hello_mss_linux.go | 164 ++++++++++++++ mtglib/server_hello_mss_linux_test.go | 302 ++++++++++++++++++++++++++ mtglib/server_hello_mss_other.go | 14 ++ network/sockopts_mss_linux.go | 42 ++++ network/sockopts_mss_linux_test.go | 124 +++++++++++ network/sockopts_mss_other.go | 17 ++ 19 files changed, 1240 insertions(+), 8 deletions(-) create mode 100644 internal/cli/client_mss.go create mode 100644 internal/cli/client_mss_test.go create mode 100644 internal/config/client_mss_test.go create mode 100644 internal/config/type_tcp_mss.go create mode 100644 mtglib/proxy_client_mss_linux_test.go create mode 100644 mtglib/server_hello_mss.go create mode 100644 mtglib/server_hello_mss_linux.go create mode 100644 mtglib/server_hello_mss_linux_test.go create mode 100644 mtglib/server_hello_mss_other.go create mode 100644 network/sockopts_mss_linux.go create mode 100644 network/sockopts_mss_linux_test.go create mode 100644 network/sockopts_mss_other.go diff --git a/example.config.toml b/example.config.toml index 8dec1a8d4..846d31d32 100644 --- a/example.config.toml +++ b/example.config.toml @@ -242,6 +242,19 @@ handshake = "10s" # Only applies to Linux and Darwin; ignored on other platforms. # tcp-not-sent-lowat = "128kib" +# Small-segment ServerHello (Linux only). Some DPI boxes recognise the FakeTLS +# ServerHello when it is sent in full-size TCP segments, but not when it is +# split into small ones. client-mss splits only the ServerHello into segments +# as if the MSS were client-mss; the rest of the session uses client-mss-bulk, +# which is set as TCP_MAXSEG on the listening socket (Linux cannot raise the +# MSS of an established connection, so the order cannot be reversed). +# client-mss: 0 (default, disabled) or 48..1460. +# client-mss-bulk: 0 or 536..65495, 1400 by default when client-mss is set; +# 0 keeps the whole session at client-mss (client-mss must then be >= 88). +# Read at start only. +# client-mss = 92 +# client-mss-bulk = 1400 + # this defines a configuration for TCP keep alives. Default values are taken # from Golang default behavior. [network.keep-alive] diff --git a/internal/cli/client_mss.go b/internal/cli/client_mss.go new file mode 100644 index 000000000..5ad34d3dd --- /dev/null +++ b/internal/cli/client_mss.go @@ -0,0 +1,42 @@ +package cli + +import ( + "github.com/9seconds/mtg/v2/internal/config" + "github.com/9seconds/mtg/v2/mtglib" + "github.com/9seconds/mtg/v2/network" +) + +// clientMSSPlan maps [network] client-mss / client-mss-bulk onto two +// mechanisms: +// - listenerMSS is TCP_MAXSEG of the listening socket, it applies to the +// whole connection; +// - serverHelloMSS splits the ServerHello alone in user space. +// +// client-mss and bulk > 0: the socket gets bulk, the ServerHello is split by +// client-mss. client-mss and bulk = 0: the whole connection runs at +// client-mss (like iptables TCPMSS). client-mss = 0: nothing. Outside Linux +// the options are ignored with a warning. +func clientMSSPlan(conf *config.Config, logger mtglib.Logger) (serverHelloMSS, listenerMSS int) { + handshake, bulk := conf.GetClientMSS() + if handshake == 0 { + return 0, 0 + } + + if !network.ListenerMSSSupported { + logger.Warning("network.client-mss is supported only on Linux; ignored") + + return 0, 0 + } + + if bulk == 0 { + serverHelloMSS, listenerMSS = 0, int(handshake) + } else { + serverHelloMSS, listenerMSS = int(handshake), int(bulk) + } + + logger.BindInt("server_hello_mss", serverHelloMSS). + BindInt("listener_mss", listenerMSS). + Info("client MSS shaping is enabled") + + return serverHelloMSS, listenerMSS +} diff --git a/internal/cli/client_mss_test.go b/internal/cli/client_mss_test.go new file mode 100644 index 000000000..d6e7107fd --- /dev/null +++ b/internal/cli/client_mss_test.go @@ -0,0 +1,49 @@ +package cli + +import ( + "testing" + + "github.com/9seconds/mtg/v2/internal/config" + "github.com/9seconds/mtg/v2/logger" + "github.com/9seconds/mtg/v2/network" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestClientMSSPlan(t *testing.T) { + cases := []struct { + name string + network string + wantHello int + wantListener int + }{ + {name: "disabled", network: "", wantHello: 0, wantListener: 0}, + {name: "ServerHello at 92, session at 1400", network: "client-mss = 92\n", wantHello: 92, wantListener: 1400}, + {name: "custom bulk", network: "client-mss = 92\nclient-mss-bulk = 1200\n", wantHello: 92, wantListener: 1200}, + {name: "whole session at 92", network: "client-mss = 92\nclient-mss-bulk = 0\n", wantHello: 0, wantListener: 92}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + conf, err := config.Parse([]byte(`bind-to = "0.0.0.0:443" +secret = "7mqFMMq3P2Tvvt_rPx5qhmFnb29nbGUuY29t" + +[network] +` + tc.network)) + require.NoError(t, err) + require.NoError(t, conf.Validate()) + + hello, listener := clientMSSPlan(conf, logger.NewNoopLogger()) + + if !network.ListenerMSSSupported { + assert.Zero(t, hello) + assert.Zero(t, listener) + + return + } + + assert.Equal(t, tc.wantHello, hello) + assert.Equal(t, tc.wantListener, listener) + }) + } +} diff --git a/internal/cli/run_proxy.go b/internal/cli/run_proxy.go index f1ce8af8b..81830c4a9 100644 --- a/internal/cli/run_proxy.go +++ b/internal/cli/run_proxy.go @@ -301,6 +301,8 @@ func runProxy(conf *config.Config, version string) error { //nolint: funlen, cyc doppelGangerURLs[i] = v.String() } + serverHelloMSS, listenerMSS := clientMSSPlan(conf, logger) + opts := mtglib.ProxyOpts{ Logger: logger, Network: ntw, @@ -326,6 +328,7 @@ func runProxy(conf *config.Config, version string) error { //nolint: funlen, cyc DoppelGangerPerRaid: conf.Defense.Doppelganger.Repeats.Get(mtglib.DoppelGangerPerRaid), DoppelGangerEach: conf.Defense.Doppelganger.UpdateEach.Get(mtglib.DoppelGangerEach), DoppelGangerDRS: conf.Defense.Doppelganger.DRS.Get(false), + ServerHelloMSS: serverHelloMSS, } proxy, err := mtglib.NewProxy(opts) @@ -333,7 +336,7 @@ func runProxy(conf *config.Config, version string) error { //nolint: funlen, cyc return fmt.Errorf("cannot create a proxy: %w", err) } - listener, err := utils.NewListener(conf.BindTo.Get(""), 0) + listener, err := utils.NewListener(conf.BindTo.Get(""), 0, listenerMSS) if err != nil { return fmt.Errorf("cannot start proxy: %w", err) } diff --git a/internal/config/client_mss_test.go b/internal/config/client_mss_test.go new file mode 100644 index 000000000..c450c71ba --- /dev/null +++ b/internal/config/client_mss_test.go @@ -0,0 +1,85 @@ +package config_test + +import ( + "testing" + + "github.com/9seconds/mtg/v2/internal/config" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func parseClientMSS(t *testing.T, network string) (*config.Config, error) { + t.Helper() + + conf, err := config.Parse([]byte(`bind-to = "0.0.0.0:443" +secret = "7mqFMMq3P2Tvvt_rPx5qhmFnb29nbGUuY29t" + +[network] +` + network)) + require.NoError(t, err) + + return conf, conf.Validate() +} + +func TestClientMSS(t *testing.T) { + cases := []struct { + name string + network string + wantHandshake uint + wantBulk uint + }{ + {name: "not set", network: "", wantHandshake: 0, wantBulk: 0}, + {name: "explicit zero", network: "client-mss = 0", wantHandshake: 0, wantBulk: 0}, + {name: "default bulk 1400", network: "client-mss = 92", wantHandshake: 92, wantBulk: 1400}, + {name: "custom bulk", network: "client-mss = 92\nclient-mss-bulk = 1200", wantHandshake: 92, wantBulk: 1200}, + {name: "bulk 0 keeps the whole session at client-mss", network: "client-mss = 92\nclient-mss-bulk = 0", wantHandshake: 92, wantBulk: 0}, + {name: "bulk without client-mss has no effect", network: "client-mss-bulk = 1400", wantHandshake: 0, wantBulk: 0}, + {name: "lower bound", network: "client-mss = 48", wantHandshake: 48, wantBulk: 1400}, + {name: "upper bounds", network: "client-mss = 1460\nclient-mss-bulk = 65495", wantHandshake: 1460, wantBulk: 65495}, + {name: "bulk lower bound", network: "client-mss = 92\nclient-mss-bulk = 536", wantHandshake: 92, wantBulk: 536}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + conf, err := parseClientMSS(t, tc.network) + require.NoError(t, err) + + handshake, bulk := conf.GetClientMSS() + assert.Equal(t, tc.wantHandshake, handshake) + assert.Equal(t, tc.wantBulk, bulk) + }) + } +} + +func TestClientMSSValidation(t *testing.T) { + cases := []struct { + name string + network string + wantErr string + }{ + {name: "client-mss below 48", network: "client-mss = 47", wantErr: "network.client-mss must be 0 or 48..1460"}, + {name: "client-mss above 1460", network: "client-mss = 1461", wantErr: "network.client-mss must be 0 or 48..1460"}, + {name: "bulk below 536", network: "client-mss = 92\nclient-mss-bulk = 535", wantErr: "network.client-mss-bulk must be 0 or 536..65495"}, + {name: "bulk above 65495", network: "client-mss = 92\nclient-mss-bulk = 65496", wantErr: "network.client-mss-bulk must be 0 or 536..65495"}, + {name: "bulk not greater than client-mss", network: "client-mss = 1400\nclient-mss-bulk = 1400", wantErr: "must be greater than network.client-mss"}, + {name: "bulk 0 and client-mss below the kernel minimum", network: "client-mss = 60\nclient-mss-bulk = 0", wantErr: "at least 88"}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + _, err := parseClientMSS(t, tc.network) + require.Error(t, err) + assert.Contains(t, err.Error(), tc.wantErr) + }) + } +} + +func TestClientMSSNotANumber(t *testing.T) { + _, err := config.Parse([]byte(`bind-to = "0.0.0.0:443" +secret = "7mqFMMq3P2Tvvt_rPx5qhmFnb29nbGUuY29t" + +[network] +client-mss = "small" +`)) + assert.Error(t, err) +} diff --git a/internal/config/config.go b/internal/config/config.go index e9a8e9625..65f32b8cc 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -71,10 +71,16 @@ type Config struct { Interval TypeDuration `json:"interval"` Count TypeConcurrency `json:"count"` } `json:"keepAlive"` - DOHIP TypeIP `json:"dohIp"` - DNS TypeDNSURI `json:"dns"` - Proxies []TypeProxyURL `json:"proxies"` - TCPNotSentLowat TypeBytes `json:"tcpNotSentLowat"` + DOHIP TypeIP `json:"dohIp"` + DNS TypeDNSURI `json:"dns"` + Proxies []TypeProxyURL `json:"proxies"` + TCPNotSentLowat TypeBytes `json:"tcpNotSentLowat"` + // ClientMSS is the MSS the FakeTLS ServerHello is split by (0 disables). + ClientMSS TypeTCPMSS `json:"clientMss"` + // ClientMSSBulk is the MSS of the rest of the session; nil means the + // key is absent (default), an explicit 0 keeps the whole session at + // ClientMSS. + ClientMSSBulk *TypeTCPMSS `json:"clientMssBulk"` } `json:"network"` Stats struct { StatsD struct { @@ -135,9 +141,74 @@ func (c *Config) Validate() error { return fmt.Errorf("incorrect bind-to parameter %s", c.BindTo.String()) } + return c.validateClientMSS() +} + +// Bounds of client-mss and client-mss-bulk. client-mss goes up to 1460 (the +// Ethernet MSS); the ServerHello is split in user space, so values below the +// kernel minimum are fine too. But with client-mss-bulk = 0 client-mss is set +// on the socket itself, and the kernel rejects TCP_MAXSEG below TCP_MIN_MSS +// (88). bulk is no less than the classic 536 and no more than the kernel limit +// (MAX_TCP_WINDOW). +const ( + ClientMSSMin = 48 + ClientMSSMax = 1460 + ClientMSSKernelMin = 88 + ClientMSSBulkMin = 536 + ClientMSSBulkMax = 65495 + + // DefaultClientMSSBulk is the MSS of the session after the ServerHello + // when client-mss is set and client-mss-bulk is not. + DefaultClientMSSBulk = 1400 +) + +func (c *Config) validateClientMSS() error { + mss := c.Network.ClientMSS.Get(0) + if mss != 0 && (mss < ClientMSSMin || mss > ClientMSSMax) { + return fmt.Errorf("network.client-mss must be 0 or %d..%d, got %d", + ClientMSSMin, ClientMSSMax, mss) + } + + if c.Network.ClientMSSBulk == nil { + return nil + } + + bulk := c.Network.ClientMSSBulk.Get(0) + if bulk != 0 && (bulk < ClientMSSBulkMin || bulk > ClientMSSBulkMax) { + return fmt.Errorf("network.client-mss-bulk must be 0 or %d..%d, got %d", + ClientMSSBulkMin, ClientMSSBulkMax, bulk) + } + + if mss != 0 && bulk == 0 && mss < ClientMSSKernelMin { + return fmt.Errorf("network.client-mss must be at least %d when network.client-mss-bulk = 0, got %d", + ClientMSSKernelMin, mss) + } + + if mss != 0 && bulk != 0 && bulk <= mss { + return fmt.Errorf("network.client-mss-bulk (%d) must be greater than network.client-mss (%d)", + bulk, mss) + } + return nil } +// GetClientMSS returns the MSS for the ServerHello and the MSS of the rest of +// the session. client-mss = 0 disables everything (0, 0); client-mss-bulk +// without client-mss has no effect. bulk = 0 keeps the whole session at +// client-mss, as iptables TCPMSS on the client SYN would. +func (c *Config) GetClientMSS() (handshake, bulk uint) { + handshake = c.Network.ClientMSS.Get(0) + if handshake == 0 { + return 0, 0 + } + + if c.Network.ClientMSSBulk == nil { + return handshake, DefaultClientMSSBulk + } + + return handshake, c.Network.ClientMSSBulk.Get(0) +} + func (c *Config) String() string { buf := &bytes.Buffer{} encoder := json.NewEncoder(buf) diff --git a/internal/config/parse.go b/internal/config/parse.go index 97eb19103..3f5922f83 100644 --- a/internal/config/parse.go +++ b/internal/config/parse.go @@ -71,6 +71,10 @@ type tomlConfig struct { DNS string `toml:"dns" json:"dns,omitempty"` Proxies []string `toml:"proxies" json:"proxies,omitempty"` TCPNotSentLowat string `toml:"tcp-not-sent-lowat" json:"tcpNotSentLowat,omitempty"` + ClientMSS uint `toml:"client-mss" json:"clientMss,omitempty"` + // A pointer tells an explicit 0 ("do not raise the MSS after the + // ServerHello") from a missing key (default 1400). + ClientMSSBulk *uint `toml:"client-mss-bulk" json:"clientMssBulk,omitempty"` } `toml:"network" json:"network,omitempty"` Stats struct { StatsD struct { diff --git a/internal/config/type_tcp_mss.go b/internal/config/type_tcp_mss.go new file mode 100644 index 000000000..89f7a9c7b --- /dev/null +++ b/internal/config/type_tcp_mss.go @@ -0,0 +1,44 @@ +package config + +import ( + "fmt" + "strconv" +) + +// TypeTCPMSS is a TCP MSS in bytes. 0 means "not set / disabled"; the valid +// ranges of client-mss and client-mss-bulk differ and are checked by +// Config.Validate. +type TypeTCPMSS struct { + Value uint +} + +func (t *TypeTCPMSS) Set(value string) error { + mss, err := strconv.ParseUint(value, 10, 16) + if err != nil { + return fmt.Errorf("value is not uint16 (%s): %w", value, err) + } + + t.Value = uint(mss) + + return nil +} + +func (t TypeTCPMSS) Get(defaultValue uint) uint { + if t.Value == 0 { + return defaultValue + } + + return t.Value +} + +func (t *TypeTCPMSS) UnmarshalJSON(data []byte) error { + return t.Set(string(data)) +} + +func (t TypeTCPMSS) MarshalJSON() ([]byte, error) { + return []byte(t.String()), nil +} + +func (t TypeTCPMSS) String() string { + return strconv.FormatUint(uint64(t.Value), 10) +} diff --git a/internal/utils/net_listener.go b/internal/utils/net_listener.go index 59b1dc11b..f08ae121c 100644 --- a/internal/utils/net_listener.go +++ b/internal/utils/net_listener.go @@ -1,6 +1,7 @@ package utils import ( + "context" "fmt" "net" @@ -26,8 +27,13 @@ func (l Listener) Accept() (net.Conn, error) { return conn, nil } -func NewListener(bindTo string, bufferSize int) (net.Listener, error) { - base, err := net.Listen("tcp", bindTo) +// NewListener opens a listening socket. listenerMSS > 0 sets TCP_MAXSEG on it +// (Linux only): this MSS is advertised to the client in the SYN-ACK and caps +// the size of segments sent to the client for the whole connection. +func NewListener(bindTo string, bufferSize int, listenerMSS int) (net.Listener, error) { + lc := net.ListenConfig{Control: network.ListenControlMSS(listenerMSS)} + + base, err := lc.Listen(context.Background(), "tcp", bindTo) if err != nil { return nil, fmt.Errorf("cannot build a base listener: %w", err) } diff --git a/mtglib/proxy.go b/mtglib/proxy.go index 1ea6f2e63..c26ad95ed 100644 --- a/mtglib/proxy.go +++ b/mtglib/proxy.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "io" "net" "strconv" "sync" @@ -45,6 +46,10 @@ type Proxy struct { allowlist IPBlocklist eventStream EventStream logger Logger + + // serverHelloMSS > 0 splits the FakeTLS ServerHello (see + // server_hello_mss.go). + serverHelloMSS int } // DomainFrontingAddress returns a host:port pair for a fronting domain. @@ -211,7 +216,19 @@ func (p *Proxy) doFakeTLSHandshake(ctx *streamContext) bool { gangerNoise := p.doppelGanger.NoiseParams() noiseParams := fake.NoiseParams{Mean: gangerNoise.Mean, Jitter: gangerNoise.Jitter} - if err := fake.SendServerHello(ctx.clientConn, p.secret.Key[:], clientHello, noiseParams); err != nil { + // The ServerHello is the only server response in the FakeTLS handshake, + // and that is what DPI looks at. With client-mss it leaves in small + // segments; the rest of the session is not affected. + var helloWriter io.Writer = ctx.clientConn + if p.serverHelloMSS > 0 { + helloWriter = fragmentedWriter{ + conn: ctx.clientConn, + mss: p.serverHelloMSS, + deadline: time.Now().Add(p.handshakeTimeout), + } + } + + if err := fake.SendServerHello(helloWriter, p.secret.Key[:], clientHello, noiseParams); err != nil { p.logger.InfoError("cannot send welcome packet", err) return false } @@ -363,6 +380,7 @@ func NewProxy(opts ProxyOpts) (*Proxy, error) { tolerateTimeSkewness: opts.getTolerateTimeSkewness(), idleTimeout: opts.getIdleTimeout(), handshakeTimeout: opts.getHandshakeTimeout(), + serverHelloMSS: opts.ServerHelloMSS, allowFallbackOnUnknownDC: opts.AllowFallbackOnUnknownDC, telegram: tg, doppelGanger: doppel.NewGanger( diff --git a/mtglib/proxy_client_mss_linux_test.go b/mtglib/proxy_client_mss_linux_test.go new file mode 100644 index 000000000..a94986db2 --- /dev/null +++ b/mtglib/proxy_client_mss_linux_test.go @@ -0,0 +1,186 @@ +//go:build linux + +package mtglib_test + +import ( + "context" + "encoding/base64" + "encoding/binary" + "encoding/json" + "io" + "net" + "os" + "path/filepath" + "testing" + "time" + + "github.com/9seconds/mtg/v2/antireplay" + "github.com/9seconds/mtg/v2/ipblocklist" + "github.com/9seconds/mtg/v2/ipblocklist/files" + "github.com/9seconds/mtg/v2/logger" + "github.com/9seconds/mtg/v2/mtglib" + "github.com/9seconds/mtg/v2/network" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/yl2chen/cidranger" + "golang.org/x/sys/unix" +) + +// The secret that signed the real ClientHello snapshots in testdata of the +// fake package. +const snapshotSecret = "ee367a189aee18fa31c190054efd4a8e9573746f726167652e676f6f676c65617069732e636f6d" + +func snapshotClientHello(t *testing.T) []byte { + t.Helper() + + data, err := os.ReadFile(filepath.Join( + "internal", "tls", "fake", "testdata", "client-hello-ok-19dfe38384b9884b.json")) + require.NoError(t, err) + + snapshot := struct { + Full string `json:"full"` + }{} + require.NoError(t, json.Unmarshal(data, &snapshot)) + + full, err := base64.StdEncoding.DecodeString(snapshot.Full) + require.NoError(t, err) + + return full +} + +// serverHelloSegments runs a real FakeTLS handshake through the proxy with +// the given ServerHelloMSS and returns how many segments the client received +// while reading the ServerHello (tcpi_segs_in), and the ServerHello size. +func serverHelloSegments(t *testing.T, serverHelloMSS int) (int, int) { + t.Helper() + + secret, err := mtglib.ParseSecret(snapshotSecret) + require.NoError(t, err) + + dialer, err := network.NewDefaultDialer(0, 0) + require.NoError(t, err) + + ntw, err := network.NewNetwork(dialer, "mtgtest", "1.1.1.1", 0) + require.NoError(t, err) + + allowlist, err := ipblocklist.NewFireholFromFiles(logger.NewNoopLogger(), 1, + []files.File{files.NewMem([]*net.IPNet{cidranger.AllIPv4, cidranger.AllIPv6})}, nil) + require.NoError(t, err) + + go allowlist.Run(time.Second) + + require.Eventually(t, func() bool { + return allowlist.Contains(net.ParseIP("127.0.0.1")) + }, 2*time.Second, 10*time.Millisecond) + + finished := streamFinished(make(chan struct{}, 1)) + + proxy, err := mtglib.NewProxy(mtglib.ProxyOpts{ + Secret: secret, + Network: ntw, + AntiReplayCache: antireplay.NewNoop(), + IPBlocklist: ipblocklist.NewNoop(), + IPAllowlist: allowlist, + EventStream: finished, + Logger: logger.NewNoopLogger(), + UseTestDCs: true, + // The ClientHello snapshot was taken in 2021. + TolerateTimeSkewness: 100 * 365 * 24 * time.Hour, + ServerHelloMSS: serverHelloMSS, + }) + require.NoError(t, err) + + defer proxy.Shutdown() + + listener, err := net.Listen("tcp4", "127.0.0.1:0") + require.NoError(t, err) + + defer listener.Close() //nolint: errcheck + + go proxy.Serve(listener) //nolint: errcheck + + conn, err := net.Dial("tcp4", listener.Addr().String()) + require.NoError(t, err) + + // Let the stream finish before Shutdown: the proxy closes active streams + // on Shutdown, which must not overlap with the handshake still going on. + defer func() { + conn.Close() //nolint: errcheck + + select { + case <-finished: + case <-time.After(5 * time.Second): + t.Error("the stream has not finished") + } + }() + + client := conn.(*net.TCPConn) //nolint: forcetypeassert + require.NoError(t, client.SetDeadline(time.Now().Add(5*time.Second))) + + before := clientTCPInfo(t, client) + + _, err = client.Write(snapshotClientHello(t)) + require.NoError(t, err) + + total := 0 + + for range 3 { // ServerHello, ChangeCipherSpec, ApplicationData + header := make([]byte, 5) + _, err := io.ReadFull(client, header) + require.NoError(t, err) + + body := make([]byte, binary.BigEndian.Uint16(header[3:])) + _, err = io.ReadFull(client, body) + require.NoError(t, err) + + total += len(header) + len(body) + } + + after := clientTCPInfo(t, client) + + return int(after.Segs_in - before.Segs_in), total +} + +func clientTCPInfo(t *testing.T, conn *net.TCPConn) *unix.TCPInfo { + t.Helper() + + rawConn, err := conn.SyscallConn() + require.NoError(t, err) + + var ( + info *unix.TCPInfo + sysErr error + ) + + require.NoError(t, rawConn.Control(func(fd uintptr) { + info, sysErr = unix.GetsockoptTCPInfo(int(fd), unix.IPPROTO_TCP, unix.TCP_INFO) + })) + require.NoError(t, sysErr) + + return info +} + +// With ServerHelloMSS the proxy sends the ServerHello in small segments (80 +// bytes of payload here), without it - in a few large ones. +func TestProxyServerHelloMSS(t *testing.T) { + plainSegs, plainSize := serverHelloSegments(t, 0) + shapedSegs, shapedSize := serverHelloSegments(t, 92) + + assert.LessOrEqual(t, plainSegs, plainSize/1000+3) + assert.GreaterOrEqual(t, shapedSegs, shapedSize/80) + + t.Logf("ServerHello without client-mss: %d bytes, %d segments; with client-mss 92: %d bytes, %d segments", + plainSize, plainSegs, shapedSize, shapedSegs) +} + +// streamFinished is an EventStream that reports the end of a stream. +type streamFinished chan struct{} + +func (s streamFinished) Send(_ context.Context, evt mtglib.Event) { + if _, ok := evt.(mtglib.EventFinish); ok { + select { + case s <- struct{}{}: + default: + } + } +} diff --git a/mtglib/proxy_opts.go b/mtglib/proxy_opts.go index 41ffa84e0..8c9435dd0 100644 --- a/mtglib/proxy_opts.go +++ b/mtglib/proxy_opts.go @@ -177,6 +177,13 @@ type ProxyOpts struct { // DoppelGangerDRS defines if TLS Dynamic Record Sizing is active. DoppelGangerDRS bool + + // ServerHelloMSS > 0 sends the FakeTLS ServerHello to the client in + // segments with a payload as at MSS = ServerHelloMSS (Linux only); the rest + // of the connection uses the regular MSS. 0 disables it. + // + // This is an optional setting. + ServerHelloMSS int } func (p ProxyOpts) valid() error { diff --git a/mtglib/server_hello_mss.go b/mtglib/server_hello_mss.go new file mode 100644 index 000000000..d9c350c93 --- /dev/null +++ b/mtglib/server_hello_mss.go @@ -0,0 +1,41 @@ +package mtglib + +import ( + "net" + "time" +) + +// Small-segment FakeTLS ServerHello (network.client-mss). +// +// Some DPI boxes recognise the FakeTLS ServerHello when it arrives in +// full-size TCP segments, but not when it is split into small ones (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; the +// rest of the session uses full-size segments. +// +// Why not "a small TCP_MAXSEG on the listener, then setsockopt a larger one": +// Linux fixes mss_clamp during the TCP handshake as min(client MSS, socket +// TCP_MAXSEG), and setsockopt(TCP_MAXSEG) on an established connection only +// changes user_mss, which no longer affects the size of outgoing segments +// (checked on 6.12: listener MSS 92, then setsockopt 1400 - tcpi_snd_mss stays +// at 80). For the same reason the MSS of an established connection cannot be +// lowered temporarily either. +// +// So the ServerHello is written in chunks that fit one segment at client-mss, +// and each next chunk is written only after the previous one has left the +// socket queue (tcpi_notsent_bytes = 0). Otherwise chunks that hit the +// congestion window or autocorking are merged by the kernel into one large +// segment: at 100 ms RTT 4 KB written in 80-byte chunks without waiting leave +// in 13 segments, with waiting - in 52. + +// fragmentedWriter writes the ServerHello in chunks of mss (see +// writeFragmented). +type fragmentedWriter struct { + conn net.Conn + mss int + deadline time.Time +} + +func (w fragmentedWriter) Write(p []byte) (int, error) { + return writeFragmented(w.conn, p, w.mss, w.deadline) +} diff --git a/mtglib/server_hello_mss_linux.go b/mtglib/server_hello_mss_linux.go new file mode 100644 index 000000000..a73f708c7 --- /dev/null +++ b/mtglib/server_hello_mss_linux.go @@ -0,0 +1,164 @@ +//go:build linux + +package mtglib + +import ( + "fmt" + "net" + "os" + "time" + + "golang.org/x/sys/unix" +) + +// tcpTimestampsOverhead is the size of the TCP timestamps option (with +// padding): the segment payload is that much smaller than the MSS when +// timestamps are negotiated. +const tcpTimestampsOverhead = 12 + +// tcpiOptTimestamps is TCPI_OPT_TIMESTAMPS of tcpi_options (linux/tcp.h); +// golang.org/x/sys/unix does not define it. +const tcpiOptTimestamps = 1 + +// serverHelloWaitMax caps the wait for one ServerHello to be sent when no +// handshake deadline is given. +const serverHelloWaitMax = 10 * time.Second + +const ( + notsentPollMin = 100 * time.Microsecond + notsentPollMax = 5 * time.Millisecond +) + +// writeFragmented writes data to a TCP connection in chunks, each of which +// leaves in its own segment with a payload no larger than at MSS = mss. If the +// connection is not TCP or mss <= 0, data is written in one go. +func writeFragmented(conn net.Conn, data []byte, mss int, deadline time.Time) (int, error) { + tcp := tcpConnOf(conn) + if tcp == nil || mss <= 0 { + return conn.Write(data) //nolint: wrapcheck + } + + rawConn, err := tcp.SyscallConn() + if err != nil { + return 0, fmt.Errorf("cannot get raw connection: %w", err) + } + + // Every chunk must leave immediately, without Nagle. Go enables + // TCP_NODELAY by default, but do not rely on it. + if err := tcp.SetNoDelay(true); err != nil { + return 0, fmt.Errorf("cannot set TCP_NODELAY: %w", err) + } + + info, err := getTCPInfo(rawConn) + if err != nil { + return 0, err + } + + chunk := segmentPayload(mss, info) + + if deadline.IsZero() { + deadline = time.Now().Add(serverHelloWaitMax) + } + + written := 0 + + for written < len(data) { + if err := waitNotSent(rawConn, deadline); err != nil { + return written, err + } + + end := min(written+chunk, len(data)) + + n, err := tcp.Write(data[written:end]) + written += n + + if err != nil { + return written, err //nolint: wrapcheck + } + } + + // Wait for the last chunk as well, otherwise the next write may be glued + // to it. + return written, waitNotSent(rawConn, deadline) +} + +// segmentPayload is the segment payload at MSS = mss: minus the timestamps +// option if it is negotiated, and no more than the current MSS of the +// connection. +func segmentPayload(mss int, info *unix.TCPInfo) int { + payload := mss + if info.Options&tcpiOptTimestamps != 0 { + payload -= tcpTimestampsOverhead + } + + if sndMSS := int(info.Snd_mss); sndMSS > 0 && payload > sndMSS { + payload = sndMSS + } + + return max(payload, 1) +} + +type rawControl interface { + Control(f func(fd uintptr)) error +} + +func getTCPInfo(rawConn rawControl) (*unix.TCPInfo, error) { + var ( + info *unix.TCPInfo + sysErr error + ) + + if err := rawConn.Control(func(fd uintptr) { + info, sysErr = unix.GetsockoptTCPInfo(int(fd), unix.IPPROTO_TCP, unix.TCP_INFO) + }); err != nil { + return nil, fmt.Errorf("cannot access socket: %w", err) + } + + if sysErr != nil { + return nil, fmt.Errorf("cannot get TCP_INFO: %w", sysErr) + } + + return info, nil +} + +// waitNotSent waits until the socket queue has no unsent bytes (bytes already +// sent but not yet acknowledged do not count). It polls with a growing pause: +// waiting is needed only when the congestion window is full, which costs a +// few RTTs per handshake. +func waitNotSent(rawConn rawControl, deadline time.Time) error { + pause := notsentPollMin + + for { + info, err := getTCPInfo(rawConn) + if err != nil { + return err + } + + if info.Notsent_bytes == 0 { + return nil + } + + if !time.Now().Before(deadline) { + return fmt.Errorf("server hello is not sent in time: %w", os.ErrDeadlineExceeded) + } + + time.Sleep(pause) + + pause = min(pause*2, notsentPollMax) + } +} + +// tcpConnOf returns the underlying TCP connection of the client: directly or +// from under the PROXY protocol wrapper. nil means it is not TCP. +func tcpConnOf(conn net.Conn) *net.TCPConn { + switch c := conn.(type) { + case *net.TCPConn: + return c + case interface{ TCPConn() (*net.TCPConn, bool) }: + if tcp, ok := c.TCPConn(); ok { + return tcp + } + } + + return nil +} diff --git a/mtglib/server_hello_mss_linux_test.go b/mtglib/server_hello_mss_linux_test.go new file mode 100644 index 000000000..1cef1f3c5 --- /dev/null +++ b/mtglib/server_hello_mss_linux_test.go @@ -0,0 +1,302 @@ +//go:build linux + +package mtglib + +import ( + "bufio" + "bytes" + "crypto/rand" + "io" + "net" + "syscall" + "testing" + "time" + + "github.com/9seconds/mtg/v2/mtglib/internal/tls" + "github.com/9seconds/mtg/v2/mtglib/internal/tls/fake" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/sys/unix" +) + +// mssTestPair opens a listener with TCP_MAXSEG = listenerMSS (0 leaves it +// alone) and returns the accepted server and the client connections. +// clientRcvBuf > 0 sets SO_RCVBUF of the client before connect (a small +// receive window). +func mssTestPair(t *testing.T, listenerMSS, clientRcvBuf int) (*net.TCPConn, *net.TCPConn) { + t.Helper() + + // network.ListenControlMSS cannot be imported from here (import cycle); + // it is tested in the network package, here the same is done directly. + lc := net.ListenConfig{Control: func(_, _ string, conn syscall.RawConn) error { + if listenerMSS <= 0 { + return nil + } + + var opErr error + + if err := conn.Control(func(fd uintptr) { + opErr = unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_MAXSEG, listenerMSS) + }); err != nil { + return err + } + + return opErr + }} + + ln, err := lc.Listen(t.Context(), "tcp4", "127.0.0.1:0") + require.NoError(t, err) + + t.Cleanup(func() { ln.Close() }) //nolint: errcheck + + dialer := net.Dialer{} + if clientRcvBuf > 0 { + dialer.Control = func(_, _ string, conn syscall.RawConn) error { + var opErr error + + err := conn.Control(func(fd uintptr) { + opErr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_RCVBUF, clientRcvBuf) + }) + if err != nil { + return err + } + + return opErr + } + } + + client, err := dialer.DialContext(t.Context(), "tcp4", ln.Addr().String()) + require.NoError(t, err) + + t.Cleanup(func() { client.Close() }) //nolint: errcheck + + server, err := ln.Accept() + require.NoError(t, err) + + t.Cleanup(func() { server.Close() }) //nolint: errcheck + + return server.(*net.TCPConn), client.(*net.TCPConn) //nolint: forcetypeassert +} + +func tcpInfoOf(t *testing.T, conn *net.TCPConn) *unix.TCPInfo { + t.Helper() + + rawConn, err := conn.SyscallConn() + require.NoError(t, err) + + info, err := getTCPInfo(rawConn) + require.NoError(t, err) + + return info +} + +// waitAllAcked waits until everything the server sent is acknowledged, so +// that tcpi_segs_out no longer changes. +func waitAllAcked(t *testing.T, conn *net.TCPConn) *unix.TCPInfo { + t.Helper() + + var info *unix.TCPInfo + + require.Eventually(t, func() bool { + info = tcpInfoOf(t, conn) + + return info.Notsent_bytes == 0 && info.Unacked == 0 + }, 5*time.Second, time.Millisecond) + + return info +} + +func readAllAsync(conn net.Conn, size int) <-chan []byte { + done := make(chan []byte, 1) + + go func() { + buf := make([]byte, size) + n, _ := io.ReadFull(conn, buf) + done <- buf[:n] + }() + + return done +} + +// The main scenario: the socket is at bulk 1400, the ServerHello (~4 KB) is +// split by 92 - at least one segment per chunk, and the data after it goes in +// large segments (tcpi_snd_mss >= 1000). +func TestWriteFragmentedSmallHelloThenBulk(t *testing.T) { + server, client := mssTestPair(t, 1400, 0) + + clientMSS, err := getsockoptMSS(client) + require.NoError(t, err) + assert.LessOrEqual(t, clientMSS, 1400) + assert.GreaterOrEqual(t, clientMSS, 1000) + + hello := make([]byte, 4096) + _, err = rand.Read(hello) + require.NoError(t, err) + + got := readAllAsync(client, len(hello)) + + before := waitAllAcked(t, server) + chunk := segmentPayload(92, before) + assert.LessOrEqual(t, chunk, 80+12) + + n, err := writeFragmented(server, hello, 92, time.Now().Add(5*time.Second)) + require.NoError(t, err) + assert.Equal(t, len(hello), n) + + afterHello := waitAllAcked(t, server) + helloSegs := int(afterHello.Segs_out - before.Segs_out) + wantSegs := (len(hello) + chunk - 1) / chunk + + assert.GreaterOrEqual(t, helloSegs, wantSegs, "the ServerHello must leave in chunks of %d bytes", chunk) + assert.Equal(t, hello, <-got) + + bulk := make([]byte, 64*1024) + got = readAllAsync(client, len(bulk)) + + _, err = server.Write(bulk) + require.NoError(t, err) + + afterBulk := waitAllAcked(t, server) + bulkSegs := int(afterBulk.Segs_out - afterHello.Segs_out) + + assert.GreaterOrEqual(t, int(afterBulk.Snd_mss), 1000) + assert.Less(t, bulkSegs, len(bulk)/500, "segments after the ServerHello must be large") + assert.Len(t, <-got, len(bulk)) + + t.Logf("ServerHello %d bytes: chunk %d, segments %d (want >= %d); "+ + "bulk 64 KB: segments %d, tcpi_snd_mss before=%d after=%d", + len(hello), chunk, helloSegs, wantSegs, bulkSegs, before.Snd_mss, afterBulk.Snd_mss) +} + +// Chunks must not be merged when sending is window-limited: a client with a +// tiny receive window does not read for 300 ms, the kernel keeps the data +// queued. Without waiting for tcpi_notsent_bytes = 0 the next chunks would be +// appended to the unsent tail of the queue and leave as one large segment. +func TestWriteFragmentedDoesNotCoalesceWhenWindowLimited(t *testing.T) { + server, client := mssTestPair(t, 1400, 2048) + + hello := make([]byte, 4096) + _, err := rand.Read(hello) + require.NoError(t, err) + + before := waitAllAcked(t, server) + chunk := segmentPayload(92, before) + + got := make(chan []byte, 1) + + go func() { + time.Sleep(300 * time.Millisecond) + + buf := make([]byte, len(hello)) + n, _ := io.ReadFull(client, buf) + got <- buf[:n] + }() + + _, err = writeFragmented(server, hello, 92, time.Now().Add(5*time.Second)) + require.NoError(t, err) + + assert.Equal(t, hello, <-got) + + after := waitAllAcked(t, server) + segs := int(after.Segs_out - before.Segs_out) + wantSegs := (len(hello) + chunk - 1) / chunk + + assert.GreaterOrEqual(t, segs, wantSegs) + t.Logf("receive window 2 KB: ServerHello of %d bytes left in %d segments (%d chunks)", len(hello), segs, wantSegs) +} + +// A real ServerHello written through fragmentedWriter is parsed by the client +// as three TLS records: splitting does not corrupt the stream. +func TestSendServerHelloThroughFragmentedWriter(t *testing.T) { + server, client := mssTestPair(t, 1400, 0) + + hello := &fake.ClientHello{CipherSuite: 4867, SessionID: make([]byte, 32)} + _, err := rand.Read(hello.SessionID) + require.NoError(t, err) + + secret := GenerateSecret("example.com") + writer := fragmentedWriter{conn: server, mss: 92, deadline: time.Now().Add(5 * time.Second)} + + before := waitAllAcked(t, server) + + errCh := make(chan error, 1) + + go func() { + errCh <- fake.SendServerHello(writer, secret.Key[:], hello, fake.NoiseParams{}) + }() + + reader := bufio.NewReader(client) + total := 0 + + for _, want := range []byte{tls.TypeHandshake, tls.TypeChangeCipherSpec, tls.TypeApplicationData} { + rec := &bytes.Buffer{} + + recordType, length, err := tls.ReadRecord(reader, rec) + require.NoError(t, err) + assert.Equal(t, want, recordType) + + total += 5 + int(length) + } + + require.NoError(t, <-errCh) + + after := waitAllAcked(t, server) + chunk := segmentPayload(92, before) + + assert.GreaterOrEqual(t, int(after.Segs_out-before.Segs_out), (total+chunk-1)/chunk) +} + +// The PROXY protocol wrapper (TCPConn()) is TCP as well: splitting reaches it. +func TestTCPConnOfUnwrapsProxyProtocol(t *testing.T) { + server, _ := mssTestPair(t, 0, 0) + + assert.Same(t, server, tcpConnOf(server)) + assert.Same(t, server, tcpConnOf(tcpWrapper{conn: server})) + assert.Nil(t, tcpConnOf(nonTCPConn{})) +} + +type tcpWrapper struct { + net.Conn + + conn *net.TCPConn +} + +func (w tcpWrapper) TCPConn() (*net.TCPConn, bool) { return w.conn, true } + +type nonTCPConn struct { + net.Conn +} + +// Not TCP: the data is written in one go, without errors. +func TestWriteFragmentedFallsBackForNonTCP(t *testing.T) { + left, right := net.Pipe() + defer left.Close() //nolint: errcheck + defer right.Close() //nolint: errcheck + + got := readAllAsync(right, 3) + + n, err := writeFragmented(left, []byte("abc"), 92, time.Time{}) + require.NoError(t, err) + assert.Equal(t, 3, n) + assert.Equal(t, []byte("abc"), <-got) +} + +func getsockoptMSS(conn *net.TCPConn) (int, error) { + rawConn, err := conn.SyscallConn() + if err != nil { + return 0, err //nolint: wrapcheck + } + + var ( + mss int + sysErr error + ) + + if err := rawConn.Control(func(fd uintptr) { + mss, sysErr = unix.GetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_MAXSEG) + }); err != nil { + return 0, err //nolint: wrapcheck + } + + return mss, sysErr //nolint: wrapcheck +} diff --git a/mtglib/server_hello_mss_other.go b/mtglib/server_hello_mss_other.go new file mode 100644 index 000000000..c5382d150 --- /dev/null +++ b/mtglib/server_hello_mss_other.go @@ -0,0 +1,14 @@ +//go:build !linux + +package mtglib + +import ( + "net" + "time" +) + +// writeFragmented writes data in one go outside Linux: client-mss needs +// TCP_INFO and tcpi_notsent_bytes, so it works only on Linux. +func writeFragmented(conn net.Conn, data []byte, _ int, _ time.Time) (int, error) { + return conn.Write(data) //nolint: wrapcheck +} diff --git a/network/sockopts_mss_linux.go b/network/sockopts_mss_linux.go new file mode 100644 index 000000000..5d96bf638 --- /dev/null +++ b/network/sockopts_mss_linux.go @@ -0,0 +1,42 @@ +//go:build linux + +package network + +import ( + "fmt" + "syscall" + + "golang.org/x/sys/unix" +) + +// ListenerMSSSupported tells whether the platform can set the MSS of a +// listening socket (TCP_MAXSEG). Outside Linux network.client-mss is ignored. +const ListenerMSSSupported = true + +// ListenControlMSS returns a Control function for net.ListenConfig that sets +// TCP_MAXSEG on the listening socket before bind/listen. Accepted connections +// inherit the value: the SYN-ACK advertises this MSS to the client, and the +// kernel never sends the client segments larger than that until the +// connection ends (mss_clamp is fixed during the handshake and cannot be +// raised later with setsockopt). mss <= 0 leaves the socket alone. +func ListenControlMSS(mss int) func(network, address string, conn syscall.RawConn) error { + return func(_, _ string, conn syscall.RawConn) error { + if mss <= 0 { + return nil + } + + var opErr error + + if err := conn.Control(func(fd uintptr) { + opErr = unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_MAXSEG, mss) + }); err != nil { + return fmt.Errorf("cannot access listener socket: %w", err) + } + + if opErr != nil { + return fmt.Errorf("cannot set TCP_MAXSEG=%d: %w", mss, opErr) + } + + return nil + } +} diff --git a/network/sockopts_mss_linux_test.go b/network/sockopts_mss_linux_test.go new file mode 100644 index 000000000..cba0a0933 --- /dev/null +++ b/network/sockopts_mss_linux_test.go @@ -0,0 +1,124 @@ +//go:build linux + +package network_test + +import ( + "io" + "net" + "testing" + + "github.com/9seconds/mtg/v2/network" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/sys/unix" +) + +func tcpMaxSeg(t *testing.T, conn net.Conn) int { + t.Helper() + + rawConn, err := conn.(*net.TCPConn).SyscallConn() //nolint: forcetypeassert + require.NoError(t, err) + + var ( + mss int + sysErr error + ) + + require.NoError(t, rawConn.Control(func(fd uintptr) { + mss, sysErr = unix.GetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_MAXSEG) + })) + require.NoError(t, sysErr) + + return mss +} + +func dialPair(t *testing.T, listenerMSS int) (net.Conn, net.Conn) { + t.Helper() + + lc := net.ListenConfig{Control: network.ListenControlMSS(listenerMSS)} + + ln, err := lc.Listen(t.Context(), "tcp4", "127.0.0.1:0") + require.NoError(t, err) + + defer ln.Close() //nolint: errcheck + + client, err := net.Dial("tcp4", ln.Addr().String()) + require.NoError(t, err) + + t.Cleanup(func() { client.Close() }) //nolint: errcheck + + server, err := ln.Accept() + require.NoError(t, err) + + t.Cleanup(func() { server.Close() }) //nolint: errcheck + + return server, client +} + +// TCP_MAXSEG of the listening socket is advertised to the client in the +// SYN-ACK: both sides then send segments no larger than that +// (client-mss-bulk = 0). +func TestListenControlMSSAdvertisedInSynAck(t *testing.T) { + server, client := dialPair(t, 92) + + clientMSS := tcpMaxSeg(t, client) + serverMSS := tcpMaxSeg(t, server) + + assert.LessOrEqual(t, clientMSS, 92) + assert.LessOrEqual(t, serverMSS, 92) + t.Logf("listener MSS 92: client TCP_MAXSEG=%d, server TCP_MAXSEG=%d", clientMSS, serverMSS) +} + +func TestListenControlMSSZeroKeepsDefault(t *testing.T) { + server, client := dialPair(t, 0) + + assert.Greater(t, tcpMaxSeg(t, client), 1000) + assert.Greater(t, tcpMaxSeg(t, server), 1000) +} + +func TestListenControlMSSRejectsTooSmall(t *testing.T) { + lc := net.ListenConfig{Control: network.ListenControlMSS(40)} + + _, err := lc.Listen(t.Context(), "tcp4", "127.0.0.1:0") + assert.Error(t, err) +} + +// This is why client-mss-bulk goes on the listener: setsockopt(TCP_MAXSEG) on +// an established connection does not raise the segment size, mss_clamp is +// fixed during the TCP handshake. +func TestTCPMaxSegCannotBeRaisedAfterAccept(t *testing.T) { + server, client := dialPair(t, 92) + + rawConn, err := server.(*net.TCPConn).SyscallConn() //nolint: forcetypeassert + require.NoError(t, err) + + var sysErr error + + require.NoError(t, rawConn.Control(func(fd uintptr) { + sysErr = unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_MAXSEG, 1400) + })) + require.NoError(t, sysErr) + + done := make(chan struct{}) + + go func() { + defer close(done) + + buf := make([]byte, 64*1024) + io.ReadFull(client, buf) //nolint: errcheck + }() + + _, err = server.Write(make([]byte, 64*1024)) + require.NoError(t, err) + <-done + + var info *unix.TCPInfo + + require.NoError(t, rawConn.Control(func(fd uintptr) { + info, sysErr = unix.GetsockoptTCPInfo(int(fd), unix.IPPROTO_TCP, unix.TCP_INFO) + })) + require.NoError(t, sysErr) + + assert.LessOrEqual(t, int(info.Snd_mss), 92) + t.Logf("listener MSS 92, then setsockopt 1400: tcpi_snd_mss=%d", info.Snd_mss) +} diff --git a/network/sockopts_mss_other.go b/network/sockopts_mss_other.go new file mode 100644 index 000000000..40f0f10e9 --- /dev/null +++ b/network/sockopts_mss_other.go @@ -0,0 +1,17 @@ +//go:build !linux + +package network + +import "syscall" + +// ListenerMSSSupported tells whether the platform can set the MSS of a +// listening socket (TCP_MAXSEG). Outside Linux network.client-mss is ignored. +const ListenerMSSSupported = false + +// ListenControlMSS does nothing outside Linux: client-mss works only on +// Linux. +func ListenControlMSS(_ int) func(network, address string, conn syscall.RawConn) error { + return func(_, _ string, _ syscall.RawConn) error { + return nil + } +} From 00657fcc7ef986e5b0a19a567b31a03964489dc8 Mon Sep 17 00:00:00 2001 From: Andrey Osipuk <45951478+AndreyOsipuk@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:17:26 +0300 Subject: [PATCH 2/5] refactor: keep NewListener signature, set client-mss-bulk via SetListenerMSS 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. --- internal/cli/run_proxy.go | 8 +- internal/utils/net_listener.go | 10 +- internal/utils/net_listener_mss.go | 60 +++++++ internal/utils/net_listener_mss_linux_test.go | 146 ++++++++++++++++++ internal/utils/net_listener_mss_test.go | 31 ++++ 5 files changed, 246 insertions(+), 9 deletions(-) create mode 100644 internal/utils/net_listener_mss.go create mode 100644 internal/utils/net_listener_mss_linux_test.go create mode 100644 internal/utils/net_listener_mss_test.go diff --git a/internal/cli/run_proxy.go b/internal/cli/run_proxy.go index 81830c4a9..5012ccc2a 100644 --- a/internal/cli/run_proxy.go +++ b/internal/cli/run_proxy.go @@ -336,11 +336,17 @@ func runProxy(conf *config.Config, version string) error { //nolint: funlen, cyc return fmt.Errorf("cannot create a proxy: %w", err) } - listener, err := utils.NewListener(conf.BindTo.Get(""), 0, listenerMSS) + listener, err := utils.NewListener(conf.BindTo.Get(""), 0) if err != nil { return fmt.Errorf("cannot start proxy: %w", err) } + if err := utils.SetListenerMSS(listener, listenerMSS); err != nil { + listener.Close() //nolint: errcheck + + return fmt.Errorf("cannot start proxy: %w", err) + } + if conf.ProxyProtocolListener.Get(false) { listener = &proxyprotocol.ListenerAdapter{ Listener: proxyproto.Listener{ diff --git a/internal/utils/net_listener.go b/internal/utils/net_listener.go index f08ae121c..59b1dc11b 100644 --- a/internal/utils/net_listener.go +++ b/internal/utils/net_listener.go @@ -1,7 +1,6 @@ package utils import ( - "context" "fmt" "net" @@ -27,13 +26,8 @@ func (l Listener) Accept() (net.Conn, error) { return conn, nil } -// NewListener opens a listening socket. listenerMSS > 0 sets TCP_MAXSEG on it -// (Linux only): this MSS is advertised to the client in the SYN-ACK and caps -// the size of segments sent to the client for the whole connection. -func NewListener(bindTo string, bufferSize int, listenerMSS int) (net.Listener, error) { - lc := net.ListenConfig{Control: network.ListenControlMSS(listenerMSS)} - - base, err := lc.Listen(context.Background(), "tcp", bindTo) +func NewListener(bindTo string, bufferSize int) (net.Listener, error) { + base, err := net.Listen("tcp", bindTo) if err != nil { return nil, fmt.Errorf("cannot build a base listener: %w", err) } diff --git a/internal/utils/net_listener_mss.go b/internal/utils/net_listener_mss.go new file mode 100644 index 000000000..1735b97d0 --- /dev/null +++ b/internal/utils/net_listener_mss.go @@ -0,0 +1,60 @@ +package utils + +import ( + "errors" + "fmt" + "net" + + "github.com/9seconds/mtg/v2/network" +) + +var errListenerNotTCP = errors.New("listener is not TCP") + +// SetListenerMSS sets TCP_MAXSEG on the listening socket of a listener made by +// NewListener (Linux only, a no-op elsewhere). Connections accepted after that +// inherit it: the SYN-ACK advertises this MSS to the client, and the kernel +// never sends the client segments larger than that for the whole connection. +// mss <= 0 leaves the socket alone. +// +// It is applied to an already listening socket on purpose, so that +// NewListener keeps its signature. Call it right after NewListener, before the +// listener is wrapped (PROXY protocol) and before Serve: a client whose SYN +// arrives in between gets the default MSS. +func SetListenerMSS(listener net.Listener, mss int) error { + if mss <= 0 { + return nil + } + + tcp, ok := tcpListenerOf(listener) + if !ok { + return fmt.Errorf("cannot set listener MSS: %w", errListenerNotTCP) + } + + rawConn, err := tcp.SyscallConn() + if err != nil { + return fmt.Errorf("cannot access listener socket: %w", err) + } + + addr := tcp.Addr() + + return network.ListenControlMSS(mss)(addr.Network(), addr.String(), rawConn) //nolint: wrapcheck +} + +// tcpListenerOf returns the TCP listener under a listener of this package or +// a plain *net.TCPListener. +func tcpListenerOf(listener net.Listener) (*net.TCPListener, bool) { + switch l := listener.(type) { + case *net.TCPListener: + return l, true + case interface{ base() net.Listener }: + return tcpListenerOf(l.base()) + } + + return nil, false +} + +// base returns the wrapped listener. The value receiver makes it available on +// both Listener and *Listener. +func (l Listener) base() net.Listener { + return l.Listener +} diff --git a/internal/utils/net_listener_mss_linux_test.go b/internal/utils/net_listener_mss_linux_test.go new file mode 100644 index 000000000..56d651ab8 --- /dev/null +++ b/internal/utils/net_listener_mss_linux_test.go @@ -0,0 +1,146 @@ +//go:build linux + +package utils_test + +import ( + "net" + "testing" + "time" + + "github.com/9seconds/mtg/v2/internal/proxyprotocol" + "github.com/9seconds/mtg/v2/internal/utils" + "github.com/pires/go-proxyproto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/sys/unix" +) + +func tcpMaxSeg(t *testing.T, conn *net.TCPConn) int { + t.Helper() + + rawConn, err := conn.SyscallConn() + require.NoError(t, err) + + var ( + mss int + sysErr error + ) + + require.NoError(t, rawConn.Control(func(fd uintptr) { + mss, sysErr = unix.GetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_MAXSEG) + })) + require.NoError(t, sysErr) + + return mss +} + +// mssListener returns a TCP listener with TCP_MAXSEG = mss set through +// SetListenerMSS on the utils.Listener wrapper (as run_proxy does after +// NewListener); connections are accepted from the TCP listener itself. +func mssListener(t *testing.T, mss int) net.Listener { + t.Helper() + + base, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + + t.Cleanup(func() { base.Close() }) //nolint: errcheck + + require.NoError(t, utils.SetListenerMSS(&utils.Listener{Listener: base}, mss)) + + return base +} + +func dial(t *testing.T, addr net.Addr) *net.TCPConn { + t.Helper() + + conn, err := net.DialTimeout("tcp", addr.String(), 2*time.Second) + require.NoError(t, err) + + t.Cleanup(func() { conn.Close() }) //nolint: errcheck + + return conn.(*net.TCPConn) //nolint: forcetypeassert +} + +// TCP_MAXSEG set on an already listening socket is inherited by connections +// accepted after that and advertised to the client in the SYN-ACK, just as +// if it were set before listen(). +func TestSetListenerMSSAppliesToAcceptedConnections(t *testing.T) { + listener := mssListener(t, 92) + client := dial(t, listener.Addr()) + + conn, err := listener.Accept() + require.NoError(t, err) + + defer conn.Close() //nolint: errcheck + + assert.LessOrEqual(t, tcpMaxSeg(t, client), 92) + assert.LessOrEqual(t, tcpMaxSeg(t, conn.(*net.TCPConn)), 92) //nolint: forcetypeassert +} + +func TestSetListenerMSSRejectsTooSmall(t *testing.T) { + base, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + + defer base.Close() //nolint: errcheck + + assert.Error(t, utils.SetListenerMSS(&utils.Listener{Listener: base}, 40)) +} + +// NewListener may return the wrapper by value; SetListenerMSS reaches the +// socket under it as well. Written without a static conversion, so that the +// test still builds if Listener implements net.Listener by pointer only. +func TestSetListenerMSSUnwrapsListenerValue(t *testing.T) { + base, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + + defer base.Close() //nolint: errcheck + + listener, ok := any(utils.Listener{Listener: base}).(net.Listener) + if !ok { + t.Skip("utils.Listener implements net.Listener by pointer only") + } + + require.NoError(t, utils.SetListenerMSS(listener, 92)) + + client := dial(t, base.Addr()) + + conn, err := base.Accept() + require.NoError(t, err) + + defer conn.Close() //nolint: errcheck + + assert.LessOrEqual(t, tcpMaxSeg(t, client), 92) +} + +// proxy-protocol-listener wraps the listener after SetListenerMSS: the +// accepted connections are PROXY protocol wrappers, the socket under them +// still has the listener MSS. +func TestSetListenerMSSBehindProxyProtocol(t *testing.T) { + for _, version := range []byte{1, 2} { + listener := mssListener(t, 92) + wrapped := &proxyprotocol.ListenerAdapter{ + Listener: proxyproto.Listener{Listener: listener}, + } + + client := dial(t, listener.Addr()) + + header := proxyproto.HeaderProxyFromAddrs(version, + &net.TCPAddr{IP: net.ParseIP("10.1.2.3"), Port: 34567}, listener.Addr()) + _, err := header.WriteTo(client) + require.NoError(t, err) + + conn, err := wrapped.Accept() + require.NoError(t, err) + + // The header is parsed lazily, on the first read or address lookup. + assert.Equal(t, "10.1.2.3:34567", conn.RemoteAddr().String()) + + tcp, ok := conn.(interface{ TCPConn() (*net.TCPConn, bool) }).TCPConn() //nolint: forcetypeassert + require.True(t, ok) + + assert.LessOrEqual(t, tcpMaxSeg(t, tcp), 92, "PROXY v%d", version) + assert.LessOrEqual(t, tcpMaxSeg(t, client), 92, "PROXY v%d", version) + + conn.Close() //nolint: errcheck + } +} diff --git a/internal/utils/net_listener_mss_test.go b/internal/utils/net_listener_mss_test.go new file mode 100644 index 000000000..6d690d66f --- /dev/null +++ b/internal/utils/net_listener_mss_test.go @@ -0,0 +1,31 @@ +package utils_test + +import ( + "net" + "testing" + + "github.com/9seconds/mtg/v2/internal/utils" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type notTCPListener struct { + net.Listener +} + +func TestSetListenerMSSZeroIsNoop(t *testing.T) { + assert.NoError(t, utils.SetListenerMSS(notTCPListener{}, 0)) +} + +func TestSetListenerMSSRejectsNonTCPListener(t *testing.T) { + assert.Error(t, utils.SetListenerMSS(notTCPListener{}, 92)) +} + +func TestSetListenerMSSAcceptsPlainTCPListener(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + + defer listener.Close() //nolint: errcheck + + assert.NoError(t, utils.SetListenerMSS(listener, 1400)) +} From f4b7e78382916a94455162bf9b773e9cbe5184ae Mon Sep 17 00:00:00 2001 From: Andrey Osipuk <45951478+AndreyOsipuk@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:17:26 +0300 Subject: [PATCH 3/5] test: cover non-reading clients, PROXY protocol and segment sizes for 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). --- mtglib/loopback_capture_linux_test.go | 185 ++++++++++++++++ mtglib/proxy.go | 14 +- mtglib/proxy_client_mss_linux_test.go | 299 ++++++++++++++++++++++++-- mtglib/server_hello_mss_linux_test.go | 22 ++ 4 files changed, 496 insertions(+), 24 deletions(-) create mode 100644 mtglib/loopback_capture_linux_test.go diff --git a/mtglib/loopback_capture_linux_test.go b/mtglib/loopback_capture_linux_test.go new file mode 100644 index 000000000..a87f5c318 --- /dev/null +++ b/mtglib/loopback_capture_linux_test.go @@ -0,0 +1,185 @@ +//go:build linux + +package mtglib_test + +import ( + "encoding/binary" + "errors" + "net" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/require" + "golang.org/x/sys/unix" +) + +// capturedSegment is one TCP data segment seen on the loopback interface. +type capturedSegment struct { + srcPort int + dstPort int + payload int + options int +} + +// loopbackCapture records TCP data segments of the loopback interface with an +// AF_PACKET socket. On lo every packet is seen twice (outgoing and incoming), +// only the incoming copy is kept. +type loopbackCapture struct { + fd int + stop chan struct{} + done chan struct{} + + mu sync.Mutex + segments []capturedSegment +} + +// startLoopbackCapture starts capturing or skips the test if the process has +// no CAP_NET_RAW. +func startLoopbackCapture(t *testing.T) *loopbackCapture { + t.Helper() + + fd, err := unix.Socket(unix.AF_PACKET, unix.SOCK_DGRAM|unix.SOCK_CLOEXEC, int(htons(unix.ETH_P_ALL))) + if errors.Is(err, unix.EPERM) || errors.Is(err, unix.EACCES) { + t.Skipf("capturing packets needs CAP_NET_RAW: %v", err) + } + + require.NoError(t, err) + + lo := loopbackInterface(t) + + require.NoError(t, unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_RCVBUF, 4<<20)) + require.NoError(t, unix.SetsockoptTimeval(fd, unix.SOL_SOCKET, unix.SO_RCVTIMEO, + &unix.Timeval{Usec: 20_000})) + require.NoError(t, unix.Bind(fd, &unix.SockaddrLinklayer{ + Protocol: htons(unix.ETH_P_ALL), + Ifindex: lo.Index, + })) + + capture := &loopbackCapture{ + fd: fd, + stop: make(chan struct{}), + done: make(chan struct{}), + } + + go capture.run() + + t.Cleanup(capture.close) + + return capture +} + +func loopbackInterface(t *testing.T) net.Interface { + t.Helper() + + ifaces, err := net.Interfaces() + require.NoError(t, err) + + for _, iface := range ifaces { + if iface.Flags&net.FlagLoopback != 0 { + return iface + } + } + + t.Skip("no loopback interface") + + return net.Interface{} +} + +func (c *loopbackCapture) run() { + defer close(c.done) + + buf := make([]byte, 65536) + + for { + select { + case <-c.stop: + return + default: + } + + n, from, err := unix.Recvfrom(c.fd, buf, 0) + if err != nil { + continue // EAGAIN on SO_RCVTIMEO, EINTR + } + + if sll, ok := from.(*unix.SockaddrLinklayer); !ok || sll.Pkttype != unix.PACKET_HOST { + continue + } + + if seg, ok := parseTCPv4(buf[:n]); ok && seg.payload > 0 { + c.mu.Lock() + c.segments = append(c.segments, seg) + c.mu.Unlock() + } + } +} + +func (c *loopbackCapture) close() { + select { + case <-c.stop: + return + default: + close(c.stop) + } + + <-c.done + unix.Close(c.fd) //nolint: errcheck +} + +// serverSegments waits until the captured traffic settles and returns the +// data segments sent to the given client port. +func (c *loopbackCapture) serverSegments(t *testing.T, serverPort int) []capturedSegment { + t.Helper() + + // The client has read everything, so all segments have passed lo; give + // the capture socket a moment to drain its queue. + time.Sleep(100 * time.Millisecond) + c.close() + + c.mu.Lock() + defer c.mu.Unlock() + + var segments []capturedSegment + + for _, seg := range c.segments { + if seg.srcPort == serverPort { + segments = append(segments, seg) + } + } + + return segments +} + +// parseTCPv4 parses an IPv4 packet (SOCK_DGRAM gives it without the link +// header) carrying TCP. +func parseTCPv4(packet []byte) (capturedSegment, bool) { + if len(packet) < 20 || packet[0]>>4 != 4 || packet[9] != unix.IPPROTO_TCP { + return capturedSegment{}, false + } + + ipHeader := int(packet[0]&0x0f) * 4 + total := int(binary.BigEndian.Uint16(packet[2:4])) + + if total > len(packet) || ipHeader+20 > total { + return capturedSegment{}, false + } + + tcp := packet[ipHeader:total] + tcpHeader := int(tcp[12]>>4) * 4 + + if tcpHeader < 20 || tcpHeader > len(tcp) { + return capturedSegment{}, false + } + + return capturedSegment{ + srcPort: int(binary.BigEndian.Uint16(tcp[0:2])), + dstPort: int(binary.BigEndian.Uint16(tcp[2:4])), + payload: len(tcp) - tcpHeader, + options: tcpHeader - 20, + }, true +} + +func htons(v uint16) uint16 { + return v<<8 | v>>8 +} diff --git a/mtglib/proxy.go b/mtglib/proxy.go index c26ad95ed..cd1eb3fac 100644 --- a/mtglib/proxy.go +++ b/mtglib/proxy.go @@ -73,7 +73,9 @@ func (p *Proxy) ServeConn(conn essentials.Conn) { ctx := newStreamContext(p.ctx, p.logger, conn) defer ctx.Close() - if err := ctx.clientConn.SetDeadline(time.Now().Add(p.handshakeTimeout)); err != nil { + handshakeDeadline := time.Now().Add(p.handshakeTimeout) + + if err := ctx.clientConn.SetDeadline(handshakeDeadline); err != nil { ctx.logger.WarningError("cannot set handshake timeout", err) return } @@ -91,7 +93,7 @@ func (p *Proxy) ServeConn(conn essentials.Conn) { ctx.logger.Info("Stream has been finished") }() - if !p.doFakeTLSHandshake(ctx) { + if !p.doFakeTLSHandshake(ctx, handshakeDeadline) { return } @@ -191,7 +193,7 @@ func (p *Proxy) Shutdown() { p.blocklist.Shutdown() } -func (p *Proxy) doFakeTLSHandshake(ctx *streamContext) bool { +func (p *Proxy) doFakeTLSHandshake(ctx *streamContext, handshakeDeadline time.Time) bool { rewind := newConnRewind(ctx.clientConn) clientHello, err := fake.ReadClientHello( @@ -218,13 +220,15 @@ func (p *Proxy) doFakeTLSHandshake(ctx *streamContext) bool { // The ServerHello is the only server response in the FakeTLS handshake, // and that is what DPI looks at. With client-mss it leaves in small - // segments; the rest of the session is not affected. + // segments; the rest of the session is not affected. Waiting for the + // segments to leave is bounded by the same handshake deadline as the + // socket, so a client that does not read cannot hold the stream longer. var helloWriter io.Writer = ctx.clientConn if p.serverHelloMSS > 0 { helloWriter = fragmentedWriter{ conn: ctx.clientConn, mss: p.serverHelloMSS, - deadline: time.Now().Add(p.handshakeTimeout), + deadline: handshakeDeadline, } } diff --git a/mtglib/proxy_client_mss_linux_test.go b/mtglib/proxy_client_mss_linux_test.go index a94986db2..53360068e 100644 --- a/mtglib/proxy_client_mss_linux_test.go +++ b/mtglib/proxy_client_mss_linux_test.go @@ -7,19 +7,24 @@ import ( "encoding/base64" "encoding/binary" "encoding/json" + "errors" + "fmt" "io" "net" "os" "path/filepath" + "syscall" "testing" "time" "github.com/9seconds/mtg/v2/antireplay" + "github.com/9seconds/mtg/v2/internal/proxyprotocol" "github.com/9seconds/mtg/v2/ipblocklist" "github.com/9seconds/mtg/v2/ipblocklist/files" "github.com/9seconds/mtg/v2/logger" "github.com/9seconds/mtg/v2/mtglib" "github.com/9seconds/mtg/v2/network" + "github.com/pires/go-proxyproto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/yl2chen/cidranger" @@ -48,10 +53,25 @@ func snapshotClientHello(t *testing.T) []byte { return full } -// serverHelloSegments runs a real FakeTLS handshake through the proxy with -// the given ServerHelloMSS and returns how many segments the client received -// while reading the ServerHello (tcpi_segs_in), and the ServerHello size. -func serverHelloSegments(t *testing.T, serverHelloMSS int) (int, int) { +// handshakeSetup tunes one test handshake through the proxy. +type handshakeSetup struct { + serverHelloMSS int + handshakeTimeout time.Duration + + // proxyProtocol > 0 puts the listener behind the PROXY protocol adapter + // (as proxy-protocol-listener = true does) and sends a header of this + // version before the ClientHello. + proxyProtocol byte + + // clientRcvBuf > 0 sets SO_RCVBUF of the client before connect. + clientRcvBuf int +} + +// startHandshake starts a proxy with the given setup on a loopback listener, +// connects to it and sends the PROXY header (if any). It returns the client +// connection and a channel that reports the end of the stream on the proxy +// side. The ClientHello is sent by sendClientHello. +func startHandshake(t *testing.T, setup handshakeSetup) (*net.TCPConn, <-chan struct{}) { t.Helper() secret, err := mtglib.ParseSecret(snapshotSecret) @@ -69,6 +89,8 @@ func serverHelloSegments(t *testing.T, serverHelloMSS int) (int, int) { go allowlist.Run(time.Second) + t.Cleanup(allowlist.Shutdown) + require.Eventually(t, func() bool { return allowlist.Contains(net.ParseIP("127.0.0.1")) }, 2*time.Second, 10*time.Millisecond) @@ -86,41 +108,92 @@ func serverHelloSegments(t *testing.T, serverHelloMSS int) (int, int) { UseTestDCs: true, // The ClientHello snapshot was taken in 2021. TolerateTimeSkewness: 100 * 365 * 24 * time.Hour, - ServerHelloMSS: serverHelloMSS, + HandshakeTimeout: setup.handshakeTimeout, + ServerHelloMSS: setup.serverHelloMSS, }) require.NoError(t, err) - defer proxy.Shutdown() - listener, err := net.Listen("tcp4", "127.0.0.1:0") require.NoError(t, err) - defer listener.Close() //nolint: errcheck + if tcpListener := listener; setup.proxyProtocol > 0 { + listener = &proxyprotocol.ListenerAdapter{ + Listener: proxyproto.Listener{Listener: tcpListener}, + } + } go proxy.Serve(listener) //nolint: errcheck - conn, err := net.Dial("tcp4", listener.Addr().String()) + clientDialer := net.Dialer{} + if setup.clientRcvBuf > 0 { + clientDialer.Control = func(_, _ string, conn syscall.RawConn) error { + var opErr error + + if err := conn.Control(func(fd uintptr) { + opErr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_RCVBUF, setup.clientRcvBuf) + }); err != nil { + return err + } + + return opErr + } + } + + conn, err := clientDialer.DialContext(t.Context(), "tcp4", listener.Addr().String()) require.NoError(t, err) + done := make(chan struct{}) + + go func() { + defer close(done) + + select { + case <-finished: + case <-time.After(10 * time.Second): + } + }() + // Let the stream finish before Shutdown: the proxy closes active streams // on Shutdown, which must not overlap with the handshake still going on. - defer func() { + t.Cleanup(func() { conn.Close() //nolint: errcheck select { - case <-finished: + case <-done: case <-time.After(5 * time.Second): t.Error("the stream has not finished") } - }() + + listener.Close() //nolint: errcheck + proxy.Shutdown() + }) client := conn.(*net.TCPConn) //nolint: forcetypeassert require.NoError(t, client.SetDeadline(time.Now().Add(5*time.Second))) - before := clientTCPInfo(t, client) + if setup.proxyProtocol > 0 { + header := proxyproto.HeaderProxyFromAddrs(setup.proxyProtocol, + &net.TCPAddr{IP: net.ParseIP("10.1.2.3"), Port: 34567}, + client.RemoteAddr()) + + _, err := header.WriteTo(client) + require.NoError(t, err) + } + + return client, done +} - _, err = client.Write(snapshotClientHello(t)) +func sendClientHello(t *testing.T, client net.Conn) { + t.Helper() + + _, err := client.Write(snapshotClientHello(t)) require.NoError(t, err) +} + +// readServerHello reads the three TLS records of the FakeTLS server response +// and returns their total size. +func readServerHello(t *testing.T, client net.Conn) int { + t.Helper() total := 0 @@ -136,9 +209,32 @@ func serverHelloSegments(t *testing.T, serverHelloMSS int) (int, int) { total += len(header) + len(body) } + return total +} + +// serverHelloSegments runs a real FakeTLS handshake through the proxy and +// returns how many segments the client received while reading the +// ServerHello (tcpi_segs_in), the largest segment payload the client has seen +// (tcpi_rcv_mss, see below) and the ServerHello size. +func serverHelloSegments(t *testing.T, setup handshakeSetup) (int, int, int) { + t.Helper() + + client, _ := startHandshake(t, setup) + + // Taken before the ClientHello: the server answers right away, and a slow + // test goroutine (-race) could otherwise miss the first segments. + before := clientTCPInfo(t, client) + + sendClientHello(t, client) + + // tcpi_segs_in also counts pure ACKs of the ClientHello, so it can only + // overstate the number of data segments; the assertions below use it as a + // lower bound for the shaped case and an upper bound for the plain one + // with a margin. + total := readServerHello(t, client) after := clientTCPInfo(t, client) - return int(after.Segs_in - before.Segs_in), total + return int(after.Segs_in - before.Segs_in), int(after.Rcv_mss), total } func clientTCPInfo(t *testing.T, conn *net.TCPConn) *unix.TCPInfo { @@ -160,17 +256,182 @@ func clientTCPInfo(t *testing.T, conn *net.TCPConn) *unix.TCPInfo { return info } +// tcpi_rcv_mss of the client is the receiver's estimate of the sender MSS: +// it starts at no more than 536 (TCP_MSS_DEFAULT) and is raised to the +// payload of any received segment that is at least as large. So it stays at +// or below 536 only if no segment above 536 bytes has arrived. This is the +// best signal of observed segment sizes available without CAP_NET_RAW; the +// exact per-segment check is TestProxyServerHelloMSSCapturedSegments. +const rcvMSSDefault = 536 + // With ServerHelloMSS the proxy sends the ServerHello in small segments (80 // bytes of payload here), without it - in a few large ones. func TestProxyServerHelloMSS(t *testing.T) { - plainSegs, plainSize := serverHelloSegments(t, 0) - shapedSegs, shapedSize := serverHelloSegments(t, 92) + plainSegs, plainRcvMSS, plainSize := serverHelloSegments(t, handshakeSetup{}) + shapedSegs, shapedRcvMSS, shapedSize := serverHelloSegments(t, handshakeSetup{serverHelloMSS: 92}) assert.LessOrEqual(t, plainSegs, plainSize/1000+3) + assert.Greater(t, plainRcvMSS, rcvMSSDefault) + assert.GreaterOrEqual(t, shapedSegs, shapedSize/80) + assert.LessOrEqual(t, shapedRcvMSS, rcvMSSDefault) + + t.Logf("ServerHello without client-mss: %d bytes, %d segments, tcpi_rcv_mss %d; "+ + "with client-mss 92: %d bytes, %d segments, tcpi_rcv_mss %d", + plainSize, plainSegs, plainRcvMSS, shapedSize, shapedSegs, shapedRcvMSS) +} + +// Behind the PROXY protocol listener (proxy-protocol-listener = true) the +// accepted connection is a wrapper, not *net.TCPConn. The ServerHello must +// still be split, for both header versions, and the handshake must succeed. +func TestProxyServerHelloMSSBehindProxyProtocol(t *testing.T) { + for _, version := range []byte{1, 2} { + t.Run(fmt.Sprintf("v%d", version), func(t *testing.T) { + segs, rcvMSS, size := serverHelloSegments(t, handshakeSetup{ + serverHelloMSS: 92, + proxyProtocol: version, + }) + + assert.GreaterOrEqual(t, segs, size/80) + assert.LessOrEqual(t, rcvMSS, rcvMSSDefault) + t.Logf("PROXY v%d: ServerHello %d bytes, %d segments, tcpi_rcv_mss %d", version, size, segs, rcvMSS) + }) + } +} + +// A client that sends the ClientHello and never reads, with a receive window +// smaller than the ServerHello: the small-segment writer has to wait for the +// window, and that wait must end at the handshake deadline, not hang the +// stream (and not go on for its own 10 s fallback either). +func TestProxyServerHelloMSSNonReadingClientRespectsDeadline(t *testing.T) { + const handshakeTimeout = 500 * time.Millisecond + + started := time.Now() + + client, finished := startHandshake(t, handshakeSetup{ + serverHelloMSS: 92, + handshakeTimeout: handshakeTimeout, + clientRcvBuf: 1024, // the kernel rounds it up to its minimum + }) + sendClientHello(t, client) + + select { + case <-finished: + case <-time.After(handshakeTimeout + 3*time.Second): + t.Fatal("the stream is still waiting for a client that does not read") + } + + elapsed := time.Since(started) + assert.GreaterOrEqual(t, elapsed, handshakeTimeout/2) + + // The window really was the limit: what the client has in its receive + // queue is not the whole server response (otherwise this test would not + // exercise the wait at all). + queued := peekQueued(t, client) + assert.False(t, hasFullServerHello(queued), "the whole ServerHello fit into the window") + + t.Logf("non-reading client: stream finished after %v, %d bytes in the client receive queue", + elapsed, len(queued)) +} + +// peekQueued returns the unread data in the receive queue of conn without +// consuming it. +func peekQueued(t *testing.T, conn *net.TCPConn) []byte { + t.Helper() + + rawConn, err := conn.SyscallConn() + require.NoError(t, err) + + buf := make([]byte, 64*1024) + + var ( + n int + sysErr error + ) + + require.NoError(t, rawConn.Control(func(fd uintptr) { + n, _, sysErr = unix.Recvfrom(int(fd), buf, unix.MSG_PEEK|unix.MSG_DONTWAIT) + })) + + if errors.Is(sysErr, unix.EAGAIN) { + return nil + } + + require.NoError(t, sysErr) + + return buf[:n] +} + +// hasFullServerHello tells whether data holds the three complete TLS records +// of the FakeTLS server response. +func hasFullServerHello(data []byte) bool { + for range 3 { + if len(data) < 5 { + return false + } + + length := 5 + int(binary.BigEndian.Uint16(data[3:5])) + if len(data) < length { + return false + } + + data = data[length:] + } + + return true +} + +// The exact check: every segment the proxy sends while writing the +// ServerHello carries payload + TCP options of at most client-mss bytes. It +// captures loopback packets with an AF_PACKET socket, which needs CAP_NET_RAW +// (root in a container has it, an unprivileged CI user does not); without it +// the test is skipped and TestProxyServerHelloMSS remains the signal. +func TestProxyServerHelloMSSCapturedSegments(t *testing.T) { + for _, tc := range []struct { + name string + setup handshakeSetup + }{ + {name: "direct", setup: handshakeSetup{serverHelloMSS: 92}}, + {name: "PROXY v2", setup: handshakeSetup{serverHelloMSS: 92, proxyProtocol: 2}}, + } { + t.Run(tc.name, func(t *testing.T) { + capture := startLoopbackCapture(t) + + client, _ := startHandshake(t, tc.setup) + sendClientHello(t, client) + size := readServerHello(t, client) + segments := capture.serverSegments(t, client.RemoteAddr().(*net.TCPAddr).Port) //nolint: forcetypeassert + + payload, largest := 0, 0 + + for _, seg := range segments { + payload += seg.payload + largest = max(largest, seg.payload+seg.options) + + assert.LessOrEqual(t, seg.payload+seg.options, 92, "segment of %d bytes + %d of options", + seg.payload, seg.options) + } + + assert.GreaterOrEqual(t, payload, size, "not all ServerHello segments were captured") + t.Logf("%s: ServerHello %d bytes in %d captured segments, the largest is %d bytes with options", + tc.name, size, len(segments), largest) + }) + } + + // Sanity check of the capture itself: without client-mss the same + // ServerHello leaves in segments far above 92 bytes. + capture := startLoopbackCapture(t) + + client, _ := startHandshake(t, handshakeSetup{}) + sendClientHello(t, client) + readServerHello(t, client) + + largest := 0 + for _, seg := range capture.serverSegments(t, client.RemoteAddr().(*net.TCPAddr).Port) { //nolint: forcetypeassert + largest = max(largest, seg.payload) + } - t.Logf("ServerHello without client-mss: %d bytes, %d segments; with client-mss 92: %d bytes, %d segments", - plainSize, plainSegs, shapedSize, shapedSegs) + assert.Greater(t, largest, 1000) } // streamFinished is an EventStream that reports the end of a stream. diff --git a/mtglib/server_hello_mss_linux_test.go b/mtglib/server_hello_mss_linux_test.go index 1cef1f3c5..0fe04aafc 100644 --- a/mtglib/server_hello_mss_linux_test.go +++ b/mtglib/server_hello_mss_linux_test.go @@ -8,6 +8,7 @@ import ( "crypto/rand" "io" "net" + "os" "syscall" "testing" "time" @@ -300,3 +301,24 @@ func getsockoptMSS(conn *net.TCPConn) (int, error) { return mss, sysErr //nolint: wrapcheck } + +// A client that never reads, with a receive window much smaller than the +// data: once the window is full, waiting for the queue to drain must stop at +// the deadline with os.ErrDeadlineExceeded instead of hanging. +func TestWriteFragmentedRespectsDeadlineWhenClientDoesNotRead(t *testing.T) { + server, _ := mssTestPair(t, 1400, 2048) + + data := make([]byte, 64*1024) + deadline := time.Now().Add(300 * time.Millisecond) + started := time.Now() + + n, err := writeFragmented(server, data, 92, deadline) + elapsed := time.Since(started) + + require.ErrorIs(t, err, os.ErrDeadlineExceeded) + assert.Less(t, n, len(data)) + assert.GreaterOrEqual(t, elapsed, 250*time.Millisecond) + assert.Less(t, elapsed, time.Second, "the write must return at the deadline") + + t.Logf("non-reading client: %d of %d bytes written, returned after %v", n, len(data), elapsed) +} From 51c758e072173738040e63b562167d05f27eea8e Mon Sep 17 00:00:00 2001 From: Andrey Osipuk <45951478+AndreyOsipuk@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:35:21 +0300 Subject: [PATCH 4/5] fix: send ServerHello chunks with MSG_EOR instead of polling the send 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). --- mtglib/proxy.go | 6 +- mtglib/proxy_client_mss_linux_test.go | 2 +- mtglib/server_hello_mss.go | 13 +- mtglib/server_hello_mss_linux.go | 117 +++++----- mtglib/server_hello_mss_linux_test.go | 293 +++++++++++++++++++++++++- mtglib/server_hello_mss_other.go | 2 +- 6 files changed, 368 insertions(+), 65 deletions(-) diff --git a/mtglib/proxy.go b/mtglib/proxy.go index 03f9b625c..8897f93e3 100644 --- a/mtglib/proxy.go +++ b/mtglib/proxy.go @@ -220,9 +220,9 @@ func (p *Proxy) doFakeTLSHandshake(ctx *streamContext, handshakeDeadline time.Ti // The ServerHello is the only server response in the FakeTLS handshake, // and that is what DPI looks at. With client-mss it leaves in small - // segments; the rest of the session is not affected. Waiting for the - // segments to leave is bounded by the same handshake deadline as the - // socket, so a client that does not read cannot hold the stream longer. + // segments; the rest of the session is not affected. Waiting for a full + // send buffer is bounded by the same handshake deadline as the socket, so + // a client that does not read cannot hold the stream longer. var helloWriter io.Writer = ctx.clientConn if p.serverHelloMSS > 0 { helloWriter = fragmentedWriter{ diff --git a/mtglib/proxy_client_mss_linux_test.go b/mtglib/proxy_client_mss_linux_test.go index 53360068e..bb812a299 100644 --- a/mtglib/proxy_client_mss_linux_test.go +++ b/mtglib/proxy_client_mss_linux_test.go @@ -302,7 +302,7 @@ func TestProxyServerHelloMSSBehindProxyProtocol(t *testing.T) { // A client that sends the ClientHello and never reads, with a receive window // smaller than the ServerHello: the small-segment writer has to wait for the // window, and that wait must end at the handshake deadline, not hang the -// stream (and not go on for its own 10 s fallback either). +// stream. func TestProxyServerHelloMSSNonReadingClientRespectsDeadline(t *testing.T) { const handshakeTimeout = 500 * time.Millisecond diff --git a/mtglib/server_hello_mss.go b/mtglib/server_hello_mss.go index d9c350c93..fdaca9cf6 100644 --- a/mtglib/server_hello_mss.go +++ b/mtglib/server_hello_mss.go @@ -22,14 +22,15 @@ import ( // lowered temporarily either. // // So the ServerHello is written in chunks that fit one segment at client-mss, -// and each next chunk is written only after the previous one has left the -// socket queue (tcpi_notsent_bytes = 0). Otherwise chunks that hit the -// congestion window or autocorking are merged by the kernel into one large -// segment: at 100 ms RTT 4 KB written in 80-byte chunks without waiting leave -// in 13 segments, with waiting - in 52. +// each sent with MSG_EOR, so that the kernel does not merge chunks that wait +// in the socket queue (congestion window, receive window, autocorking) into +// one large segment, and does not collapse them on retransmission either: at +// 100 ms RTT 4 KB written in 80-byte chunks leave in 11-13 segments without it +// and in 52 with it (kernel 6.12, netem). // fragmentedWriter writes the ServerHello in chunks of mss (see -// writeFragmented). +// writeFragmented). A full send buffer is waited for no longer than deadline +// (the handshake deadline). type fragmentedWriter struct { conn net.Conn mss int diff --git a/mtglib/server_hello_mss_linux.go b/mtglib/server_hello_mss_linux.go index a73f708c7..36cd9380d 100644 --- a/mtglib/server_hello_mss_linux.go +++ b/mtglib/server_hello_mss_linux.go @@ -3,9 +3,12 @@ package mtglib import ( + "errors" "fmt" + "io" "net" "os" + "syscall" "time" "golang.org/x/sys/unix" @@ -20,18 +23,26 @@ const tcpTimestampsOverhead = 12 // golang.org/x/sys/unix does not define it. const tcpiOptTimestamps = 1 -// serverHelloWaitMax caps the wait for one ServerHello to be sent when no -// handshake deadline is given. -const serverHelloWaitMax = 10 * time.Second - -const ( - notsentPollMin = 100 * time.Microsecond - notsentPollMax = 5 * time.Millisecond -) +// sendmsgFunc is the signature of unix.SendmsgN. sendChunks takes it as an +// argument so that tests can check the flags and the bounds of every call. +type sendmsgFunc func(fd int, p, oob []byte, to unix.Sockaddr, flags int) (int, error) // writeFragmented writes data to a TCP connection in chunks, each of which // leaves in its own segment with a payload no larger than at MSS = mss. If the // connection is not TCP or mss <= 0, data is written in one go. +// +// Each chunk is sent with sendmsg(MSG_EOR). The kernel never appends data to +// an skb marked EOR and never collapses it with the next one on +// retransmission (tcp_retrans_collapse), so chunks are not merged when they +// wait in the queue for the congestion window, the receive window or +// autocorking, and a retransmitted ServerHello still leaves in small +// segments. Without it, 4 KB written in 80-byte chunks at 100 ms RTT leave in +// 11-13 segments instead of 52 (kernel 6.12, netem). +// +// There is no polling: a write blocks only when the send buffer is full, and +// then it waits for the socket to become writable. The wait is bounded by +// deadline, which becomes the write deadline of the connection; a zero +// deadline keeps the write deadline the connection already has. func writeFragmented(conn net.Conn, data []byte, mss int, deadline time.Time) (int, error) { tcp := tcpConnOf(conn) if tcp == nil || mss <= 0 { @@ -49,37 +60,66 @@ func writeFragmented(conn net.Conn, data []byte, mss int, deadline time.Time) (i return 0, fmt.Errorf("cannot set TCP_NODELAY: %w", err) } + if !deadline.IsZero() { + if err := tcp.SetWriteDeadline(deadline); err != nil { + return 0, fmt.Errorf("cannot set write deadline: %w", err) + } + } + info, err := getTCPInfo(rawConn) if err != nil { return 0, err } - chunk := segmentPayload(mss, info) + return sendChunks(rawConn, data, segmentPayload(mss, info), unix.SendmsgN) +} + +// sendChunks sends data in chunks of chunk bytes, each one with MSG_EOR. +// +// A partial send (the send buffer filled up in the middle of a chunk) is not +// marked EOR by the kernel, so the rest of the same chunk, sent next with +// MSG_EOR, joins it in the same skb and the chunk still leaves as one +// segment. Chunk boundaries are therefore counted from the start of data, not +// from the last write. +func sendChunks(rawConn syscall.RawConn, data []byte, chunk int, sendmsg sendmsgFunc) (int, error) { + var ( + written int + sendErr error + ) - if deadline.IsZero() { - deadline = time.Now().Add(serverHelloWaitMax) - } + err := rawConn.Write(func(fd uintptr) bool { + for written < len(data) { + end := min((written/chunk+1)*chunk, len(data)) - written := 0 + n, err := sendmsg(int(fd), data[written:end], nil, nil, unix.MSG_EOR|unix.MSG_NOSIGNAL) - for written < len(data) { - if err := waitNotSent(rawConn, deadline); err != nil { - return written, err - } + switch { + case errors.Is(err, unix.EINTR): + continue + case errors.Is(err, unix.EAGAIN): + // The send buffer is full: wait until the socket is + // writable (or the write deadline passes). + return false + case err != nil: + sendErr = os.NewSyscallError("sendmsg", err) - end := min(written+chunk, len(data)) + return true + case n <= 0: + sendErr = io.ErrShortWrite - n, err := tcp.Write(data[written:end]) - written += n + return true + } - if err != nil { - return written, err //nolint: wrapcheck + written += n } + + return true + }) + if err != nil { + return written, fmt.Errorf("cannot send server hello: %w", err) } - // Wait for the last chunk as well, otherwise the next write may be glued - // to it. - return written, waitNotSent(rawConn, deadline) + return written, sendErr } // segmentPayload is the segment payload at MSS = mss: minus the timestamps @@ -121,33 +161,6 @@ func getTCPInfo(rawConn rawControl) (*unix.TCPInfo, error) { return info, nil } -// waitNotSent waits until the socket queue has no unsent bytes (bytes already -// sent but not yet acknowledged do not count). It polls with a growing pause: -// waiting is needed only when the congestion window is full, which costs a -// few RTTs per handshake. -func waitNotSent(rawConn rawControl, deadline time.Time) error { - pause := notsentPollMin - - for { - info, err := getTCPInfo(rawConn) - if err != nil { - return err - } - - if info.Notsent_bytes == 0 { - return nil - } - - if !time.Now().Before(deadline) { - return fmt.Errorf("server hello is not sent in time: %w", os.ErrDeadlineExceeded) - } - - time.Sleep(pause) - - pause = min(pause*2, notsentPollMax) - } -} - // tcpConnOf returns the underlying TCP connection of the client: directly or // from under the PROXY protocol wrapper. nil means it is not TCP. func tcpConnOf(conn net.Conn) *net.TCPConn { diff --git a/mtglib/server_hello_mss_linux_test.go b/mtglib/server_hello_mss_linux_test.go index 0fe04aafc..f1e655c8a 100644 --- a/mtglib/server_hello_mss_linux_test.go +++ b/mtglib/server_hello_mss_linux_test.go @@ -6,6 +6,7 @@ import ( "bufio" "bytes" "crypto/rand" + "errors" "io" "net" "os" @@ -171,8 +172,8 @@ func TestWriteFragmentedSmallHelloThenBulk(t *testing.T) { // Chunks must not be merged when sending is window-limited: a client with a // tiny receive window does not read for 300 ms, the kernel keeps the data -// queued. Without waiting for tcpi_notsent_bytes = 0 the next chunks would be -// appended to the unsent tail of the queue and leave as one large segment. +// queued. Without MSG_EOR the next chunks would be appended to the unsent tail +// of the queue and leave as one large segment. func TestWriteFragmentedDoesNotCoalesceWhenWindowLimited(t *testing.T) { server, client := mssTestPair(t, 1400, 2048) @@ -322,3 +323,291 @@ func TestWriteFragmentedRespectsDeadlineWhenClientDoesNotRead(t *testing.T) { t.Logf("non-reading client: %d of %d bytes written, returned after %v", n, len(data), elapsed) } + +func setSndBuf(t *testing.T, conn *net.TCPConn, size int) { + t.Helper() + + rawConn, err := conn.SyscallConn() + require.NoError(t, err) + + var opErr error + + require.NoError(t, rawConn.Control(func(fd uintptr) { + opErr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_SNDBUF, size) + })) + require.NoError(t, opErr) +} + +// A full send buffer: the client does not read for a while, the server's send +// buffer is small, so sendmsg returns EAGAIN and partial sends in the middle +// of a chunk. The write waits for the socket to become writable, the data +// arrives intact, and every chunk still leaves in its own segment: the rest +// of a partially sent chunk joins it, not the next chunk. +func TestWriteFragmentedSendBufferFull(t *testing.T) { + server, client := mssTestPair(t, 1400, 2048) + setSndBuf(t, server, 4096) + + hello := make([]byte, 16*1024) + _, err := rand.Read(hello) + require.NoError(t, err) + + before := waitAllAcked(t, server) + chunk := segmentPayload(92, before) + + got := make(chan []byte, 1) + + go func() { + time.Sleep(300 * time.Millisecond) + + buf := make([]byte, len(hello)) + n, _ := io.ReadFull(client, buf) + got <- buf[:n] + }() + + n, err := writeFragmented(server, hello, 92, time.Now().Add(5*time.Second)) + require.NoError(t, err) + assert.Equal(t, len(hello), n) + assert.Equal(t, hello, <-got) + + after := waitAllAcked(t, server) + segs := int(after.Segs_out - before.Segs_out) + wantSegs := (len(hello) + chunk - 1) / chunk + + assert.GreaterOrEqual(t, segs, wantSegs) + t.Logf("send buffer 4 KB, receive window 2 KB: %d bytes left in %d segments (%d chunks)", + len(hello), segs, wantSegs) +} + +// With a zero deadline the write deadline the connection already has applies: +// a client that never reads cannot hold the write past it. +func TestWriteFragmentedZeroDeadlineKeepsConnDeadline(t *testing.T) { + server, _ := mssTestPair(t, 1400, 2048) + setSndBuf(t, server, 4096) + + require.NoError(t, server.SetWriteDeadline(time.Now().Add(300*time.Millisecond))) + + started := time.Now() + _, err := writeFragmented(server, make([]byte, 1<<20), 92, time.Time{}) + + require.ErrorIs(t, err, os.ErrDeadlineExceeded) + assert.Less(t, time.Since(started), 3*time.Second) +} + +// sendmsgCall is one call of a fake sendmsg. +type sendmsgCall struct { + data []byte + flags int +} + +// fakeSendmsg records every call and answers it with the next result; once +// the results run out, it sends everything it is given. +type fakeSendmsg struct { + calls []sendmsgCall + results []fakeSendmsgResult + + // wake makes the socket report readiness again after a fake EAGAIN (see + // fakeSendmsgConn). + wake func() +} + +type fakeSendmsgResult struct { + n int + err error +} + +func (f *fakeSendmsg) sendmsg(_ int, p, _ []byte, _ unix.Sockaddr, flags int) (int, error) { + f.calls = append(f.calls, sendmsgCall{data: bytes.Clone(p), flags: flags}) + + if len(f.results) == 0 { + return len(p), nil + } + + res := f.results[0] + f.results = f.results[1:] + + if errors.Is(res.err, unix.EAGAIN) { + f.wake() + } + + if res.err != nil { + return -1, res.err + } + + return res.n, nil +} + +// fakeSendmsgConn returns a fake sendmsg on top of a real server socket. +// +// After a fake EAGAIN the runtime poller waits for a new readiness event +// (edge-triggered epoll), which an idle writable socket never produces; a real +// EAGAIN sets SOCK_NOSPACE and the kernel wakes the socket once there is room. +// So on a fake EAGAIN the client sends a byte: the wakeup reports the socket +// as writable as well. The write deadline turns a missed wakeup into a test +// failure instead of a hang. +func fakeSendmsgConn(t *testing.T, results []fakeSendmsgResult) (syscall.RawConn, *fakeSendmsg) { + t.Helper() + + server, client := mssTestPair(t, 0, 0) + require.NoError(t, server.SetWriteDeadline(time.Now().Add(5*time.Second))) + + rawConn, err := server.SyscallConn() + require.NoError(t, err) + + return rawConn, &fakeSendmsg{ + results: results, + wake: func() { + client.Write([]byte{0}) //nolint: errcheck + }, + } +} + +func patternData(size int) []byte { + data := make([]byte, size) + for i := range data { + data[i] = byte(i % 251) + } + + return data +} + +// Every chunk is one sendmsg call with MSG_EOR: this is what keeps the kernel +// from merging chunks in the queue and from collapsing them on retransmission +// (see TestWriteFragmentedRetransmissionIsNotCollapsed for the kernel side). +func TestSendChunksMarksEveryChunkEOR(t *testing.T) { + data := patternData(250) + rawConn, fake := fakeSendmsgConn(t, nil) + + n, err := sendChunks(rawConn, data, 80, fake.sendmsg) + require.NoError(t, err) + assert.Equal(t, len(data), n) + + want := [][]byte{data[0:80], data[80:160], data[160:240], data[240:250]} + require.Len(t, fake.calls, len(want)) + + for i, call := range fake.calls { + assert.Equal(t, want[i], call.data, "call %d", i) + assert.NotZero(t, call.flags&unix.MSG_EOR, "call %d has no MSG_EOR", i) + assert.NotZero(t, call.flags&unix.MSG_NOSIGNAL, "call %d has no MSG_NOSIGNAL", i) + } +} + +// A partial send, EINTR and EAGAIN in the middle of a chunk: the rest of the +// same chunk is sent next (boundaries are counted from the start of data, not +// from the last write), EAGAIN waits for the socket to become writable, and +// the data is sent exactly once. +func TestSendChunksPartialSendAndEAGAIN(t *testing.T) { + data := patternData(200) + rawConn, fake := fakeSendmsgConn(t, []fakeSendmsgResult{ + {n: 30}, + {err: unix.EINTR}, + {err: unix.EAGAIN}, + {n: 20}, + {n: 30}, + }) + + n, err := sendChunks(rawConn, data, 80, fake.sendmsg) + require.NoError(t, err) + assert.Equal(t, len(data), n) + + want := [][]byte{ + data[0:80], // 30 sent + data[30:80], // EINTR + data[30:80], // EAGAIN + data[30:80], // 20 sent + data[50:80], // 30 sent, the end of the first chunk + data[80:160], // the second chunk, whole + data[160:200], // the tail + } + require.Len(t, fake.calls, len(want)) + + for i, call := range fake.calls { + assert.Equal(t, want[i], call.data, "call %d", i) + assert.NotZero(t, call.flags&unix.MSG_EOR, "call %d has no MSG_EOR", i) + } +} + +// A send error stops the write and reports how much was sent before it. +func TestSendChunksReportsSendError(t *testing.T) { + rawConn, fake := fakeSendmsgConn(t, []fakeSendmsgResult{{n: 80}, {err: unix.EPIPE}}) + + n, err := sendChunks(rawConn, patternData(200), 80, fake.sendmsg) + + require.ErrorIs(t, err, unix.EPIPE) + assert.Equal(t, 80, n) + assert.Len(t, fake.calls, 2) +} + +// setDropAll attaches (or detaches) a socket filter that drops every packet +// arriving at conn, so that conn does not acknowledge anything. +func setDropAll(t *testing.T, conn *net.TCPConn, drop bool) { + t.Helper() + + rawConn, err := conn.SyscallConn() + require.NoError(t, err) + + var opErr error + + require.NoError(t, rawConn.Control(func(fd uintptr) { + if !drop { + opErr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_DETACH_FILTER, 0) + + return + } + + filter := []unix.SockFilter{{Code: unix.BPF_RET | unix.BPF_K, K: 0}} + opErr = unix.SetsockoptSockFprog(int(fd), unix.SOL_SOCKET, unix.SO_ATTACH_FILTER, &unix.SockFprog{ + Len: uint16(len(filter)), + Filter: &filter[0], + }) + })) + require.NoError(t, opErr) +} + +// A lost ServerHello is retransmitted in the same small segments. The client +// drops everything it receives, so nothing is acknowledged and the server +// retransmits on RTO. Without MSG_EOR the kernel collapses the small skbs of +// the retransmission queue into one full segment (tcp_retrans_collapse, on by +// default): on a lossy path the ServerHello would go out in large segments +// exactly when splitting matters. +func TestWriteFragmentedRetransmissionIsNotCollapsed(t *testing.T) { + server, client := mssTestPair(t, 1400, 0) + + before := waitAllAcked(t, server) + chunk := segmentPayload(92, before) + + // Fewer chunks than the initial congestion window, so that all of them + // are sent at once and wait in the retransmission queue together. + hello := make([]byte, 8*chunk) + _, err := rand.Read(hello) + require.NoError(t, err) + + setDropAll(t, client, true) + + _, err = writeFragmented(server, hello, 92, time.Now().Add(5*time.Second)) + require.NoError(t, err) + + var lost *unix.TCPInfo + + require.Eventually(t, func() bool { + lost = tcpInfoOf(t, server) + + return lost.Retransmits > 0 + }, 10*time.Second, time.Millisecond, "no retransmission timeout") + + got := readAllAsync(client, len(hello)) + + setDropAll(t, client, false) + + assert.Equal(t, hello, <-got) + + after := waitAllAcked(t, server) + retransSegs := int(after.Total_retrans - before.Total_retrans) + retransBytes := int(after.Bytes_retrans - before.Bytes_retrans) + + require.Positive(t, retransSegs) + assert.LessOrEqual(t, retransBytes, retransSegs*chunk, + "retransmitted segments must stay at %d bytes of payload", chunk) + + t.Logf("ServerHello of %d bytes in chunks of %d: %d bytes retransmitted in %d segments", + len(hello), chunk, retransBytes, retransSegs) +} diff --git a/mtglib/server_hello_mss_other.go b/mtglib/server_hello_mss_other.go index c5382d150..ac62d822f 100644 --- a/mtglib/server_hello_mss_other.go +++ b/mtglib/server_hello_mss_other.go @@ -8,7 +8,7 @@ import ( ) // writeFragmented writes data in one go outside Linux: client-mss needs -// TCP_INFO and tcpi_notsent_bytes, so it works only on Linux. +// TCP_INFO and MSG_EOR on TCP, so it works only on Linux. func writeFragmented(conn net.Conn, data []byte, _ int, _ time.Time) (int, error) { return conn.Write(data) //nolint: wrapcheck } From e05e80d08409903871700678ce398aff9ff7df76 Mon Sep 17 00:00:00 2001 From: Andrey Osipuk <45951478+AndreyOsipuk@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:23:12 +0300 Subject: [PATCH 5/5] test: skip the retransmission test where socket filters are not permitted --- mtglib/server_hello_mss_linux_test.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/mtglib/server_hello_mss_linux_test.go b/mtglib/server_hello_mss_linux_test.go index f1e655c8a..7a9afbc1d 100644 --- a/mtglib/server_hello_mss_linux_test.go +++ b/mtglib/server_hello_mss_linux_test.go @@ -560,6 +560,13 @@ func setDropAll(t *testing.T, conn *net.TCPConn, drop bool) { Filter: &filter[0], }) })) + + // Some CI sandboxes do not allow socket filters for unprivileged + // processes; the test needs one to stop acknowledgements. + if drop && (errors.Is(opErr, unix.EPERM) || errors.Is(opErr, unix.EACCES)) { + t.Skipf("attaching a socket filter is not permitted here: %v", opErr) + } + require.NoError(t, opErr) }